
' This file implements the TableControl, TableControlRow, and RecordControl classes for the 
' ShowProductsTablePage.aspx page.  The Row or RecordControl classes are the 
' ideal place to add code customizations. For example, you can override the LoadData, 
' CreateWhereClause, DataBind, SaveData, GetUIData, and Validate methods.

#Region "Imports statements"

Option Strict On
Imports Microsoft.VisualBasic
Imports BaseClasses.Web.UI.WebControls
Imports System
Imports System.Collections
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports BaseClasses
Imports BaseClasses.Data
Imports BaseClasses.Utils
Imports ReportTools.ReportCreator
Imports ReportTools.Shared

  
        
Imports Training1.Business
Imports Training1.Data
        

#End Region

  
Namespace Training1.UI.Controls.ShowProductsTablePage

#Region "Section 1: Place your customizations here."

    
Public Class ProductsTableControlRow
        Inherits BaseProductsTableControlRow
        ' The BaseProductsTableControlRow implements code for a ROW within the
        ' the ProductsTableControl table.  The BaseProductsTableControlRow implements the DataBind and SaveData methods.
        ' The loading of data is actually performed by the LoadData method in the base class of ProductsTableControl.

        ' This is the ideal place to add your code customizations. For example, you can override the DataBind, 
        ' SaveData, GetUIData, and Validate methods.
        

End Class

  

Public Class ProductsTableControl
        Inherits BaseProductsTableControl

        ' The BaseProductsTableControl class implements the LoadData, DataBind, CreateWhereClause
        ' and other methods to load and display the data in a table control.

        ' This is the ideal place to add your code customizations. You can override the LoadData and CreateWhereClause,
        ' The ProductsTableControlRow class offers another place where you can customize
        ' the DataBind, GetUIData, SaveData and Validate methods specific to each row displayed on the table.


        ''' <summary>
        ''' This method is called when MarkDiscontinued is clicked. 
        ''' </summary>
Public Overrides Sub MarkDiscontinued_Click(ByVal sender As Object, ByVal args As EventArgs)
    Dim rc As ProductsTableControlRow

    Try
        DbUtils.StartTransaction()

        ' Get all of the selected record controls.  Record controls are UI controls.
        For Each rc In Me.GetSelectedRecordControls()
            Dim rec As ProductsRecord

            ' Using the RecordUniqueId, read the Product record from the database.
            ' Use True as the second argument to make sure you get a Writable record.
            rec = ProductsTable.GetRecord(rc.RecordUniqueId, True)
            If Not (IsNothing(rec)) Then
                ' Mark as Discontinued
                rec.Discontinued = True
                rec.Save()
            End If
        Next

        DbUtils.CommitTransaction()
    Catch ex As Exception
        Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
    Finally
        DbUtils.EndTransaction()
    End Try

    ' Mark the data as changed so the data is refreshed
    Me.DataChanged = True
End Sub
            
        ''' <summary>
        '''     This method is called when UnmarkDiscontinued is clicked. 
        ''' </summary>            
        Public Overrides Sub UnmarkDiscontinued_Click(ByVal sender As Object, ByVal args As EventArgs)
            Dim rc As ProductsTableControlRow

            Try
                DbUtils.StartTransaction()

                ' Get all of the selected record controls.  Record controls are UI controls.
                For Each rc In Me.GetSelectedRecordControls()
                    Dim rec As ProductsRecord

                    ' Using the RecordUniqueId, read the Product record from the database.
                    ' Use True as the second argument to make sure you get a Writable record.
                    rec = ProductsTable.GetRecord(rc.RecordUniqueId, True)
                    If Not (IsNothing(rec)) Then
                        ' Unmark as Discontinued
                        rec.Discontinued = False
                        rec.Save()
                    End If
                Next

                DbUtils.CommitTransaction()
            Catch ex As Exception
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
                DbUtils.EndTransaction()
            End Try
            ' Mark the data as changed so the data is refreshed
            Me.DataChanged = True
        End Sub


        Public Overrides Function CreateWhereClause() As WhereClause
            Dim wc As WhereClause = MyBase.CreateWhereClause()
            If (IsNothing(wc)) Then
                wc = New WhereClause
            End If

            ' Return where clause if this is a postback.  Only use URL parameters on first load.
            If Me.Page.IsPostBack Then Return wc

            ' Get the url value
            Dim Supplier As String = Me.Page.Request.QueryString("Supplier")
            Dim Category As String = Me.Page.Request.QueryString("Category")

            If Not (IsNothing(Supplier)) Then wc.iAND(ProductsTable.SupplierID, BaseFilter.ComparisonOperator.EqualsTo, Supplier, True)
            If Not (IsNothing(Category)) Then wc.iAND(ProductsTable.CategoryID, BaseFilter.ComparisonOperator.EqualsTo, Category, True)

            ' if you only want to filter the table when the page loads first time
            ' then you need to check for Postback and add whereclause if its not a Postback    
            ' Add additional Where Clause here    
            Return wc
        End Function

        Protected Overrides Sub PopulateSupplierIDFilter(ByVal selectedValue As String, ByVal maxItems As Integer)
            MyBase.PopulateSupplierIDFilter(selectedValue, maxItems)

            Dim urlValue As String = Me.Page.Request.QueryString("Supplier")
            If Not Me.Page.IsPostBack AndAlso Not IsNothing(urlValue) Then
                Dim li As ListItem = Me.SupplierIDFilter.Items.FindByText(urlValue)
                If Not (IsNothing(li)) Then li.Selected = True
            End If
        End Sub

        Protected Overrides Sub PopulateCategoryIdFilter(ByVal selectedValue As String, ByVal maxItems As Integer)
            MyBase.PopulateCategoryIdFilter(selectedValue, maxItems)

            Dim urlValue As String = Me.Page.Request.QueryString("Category")
            If Not Me.Page.IsPostBack AndAlso Not IsNothing(urlValue) Then
                Dim li As ListItem = Me.CategoryIdFilter.Items.FindByText(urlValue)
                If Not (IsNothing(li)) Then li.Selected = True
            End If
        End Sub

    End Class


  

#End Region

  

#Region "Section 2: Do not modify this section."
    
    
' Base class for the ProductsTableControlRow control on the ShowProductsTablePage page.
' Do not modify this class. Instead override any method in ProductsTableControlRow.
Public Class BaseProductsTableControlRow
        Inherits Training1.UI.BaseApplicationRecordControl

        '  To customize, override this method in ProductsTableControlRow.
      Protected Overridable Sub Control_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Init

      
      
            ' Register the event handlers.
        
              AddHandler Me.ProductsRowCopyButton.Click, AddressOf ProductsRowCopyButton_Click
              AddHandler Me.ProductsRowDeleteButton.Click, AddressOf ProductsRowDeleteButton_Click
              AddHandler Me.ProductsRowEditButton.Click, AddressOf ProductsRowEditButton_Click
              AddHandler Me.ProductsRowViewButton.Click, AddressOf ProductsRowViewButton_Click
        End Sub

        '  To customize, override this method in ProductsTableControlRow.
        Protected Overridable Sub Control_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        
                ' Show confirmation message on Click
                Me.ProductsRowDeleteButton.Attributes.Add("onClick", "return (confirm('" & (CType(Me.Page,BaseApplicationPage)).GetResourceValue("DeleteRecordConfirm", "Training1") & "'));")
        End Sub

        ' Read data from database.  To customize, override this method in ProductsTableControlRow.
        Public Overridable Sub LoadData()        
        
            If Not Me.RecordUniqueId Is Nothing AndAlso Me.RecordUniqueId.Trim <> "" Then
                Me.DataSource = ProductsTable.GetRecord(Me.RecordUniqueId, True)
                Return
            End If
        
            ' Since this is a row in the table, the data for this row is loaded by the 
            ' LoadData method of the BaseProductsTableControl when the data for the entire
            ' table is loaded.
            Me.DataSource = New ProductsRecord()
          
        End Sub

        ' Populate the UI controls using the DataSource.  To customize, override this method in ProductsTableControlRow.
        Public Overrides Sub DataBind()

            MyBase.DataBind()

            ' Make sure that the DataSource is initialized.
            If Me.DataSource Is Nothing Then
                Return
            End If
        
      
            ' For each field, check to see if a value is specified.  If a value is specified,
            ' then format the value for display.  If no value is specified, use the default value (formatted).

        
            If Me.DataSource.CategoryIDSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(ProductsTable.CategoryID)
                formattedValue = HttpUtility.HtmlEncode(formattedValue)
                If Not formattedValue is Nothing Then
                              
                    Dim maxLength as Integer = Len(formattedValue)
                    If (maxLength > CType(100, Integer)) Then
                        maxLength = CType(100, Integer)
                        
                    End If                    
                        If maxLength = CType(100, Integer) Then
                            formattedValue= NetUtils.EncodeStringForHtmlDisplay(formattedValue.SubString(0,MaxLength))
                            formattedValue = formattedValue & "..."
                            
                        End If
                    
                End If  
                            
                Me.CategoryID.Text = formattedValue
              
            Else      
                Me.CategoryID.Text = ProductsTable.CategoryID.Format(ProductsTable.CategoryID.DefaultValue)
              
            End If
                    
            If Me.CategoryID.Text Is Nothing _
                OrElse Me.CategoryID.Text.Trim() = "" Then
                Me.CategoryID.Text = "&nbsp;"
            End If
                  
            If Me.DataSource.DiscontinuedSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(ProductsTable.Discontinued, "Yes,No")
                formattedValue = HttpUtility.HtmlEncode(formattedValue)
                If Not formattedValue is Nothing Then
                              
                    Dim maxLength as Integer = Len(formattedValue)
                    If (maxLength > CType(100, Integer)) Then
                        maxLength = CType(100, Integer)
                        
                    End If                    
                        If maxLength = CType(100, Integer) Then
                            formattedValue= NetUtils.EncodeStringForHtmlDisplay(formattedValue.SubString(0,MaxLength))
                            formattedValue = formattedValue & "..."
                            
                        End If
                    
                End If  
                            
                Me.Discontinued.Text = formattedValue
              
            Else      
                Me.Discontinued.Text = ProductsTable.Discontinued.Format(ProductsTable.Discontinued.DefaultValue, "Yes,No")
              
            End If
                    
            If Me.Discontinued.Text Is Nothing _
                OrElse Me.Discontinued.Text.Trim() = "" Then
                Me.Discontinued.Text = "&nbsp;"
            End If
                  
            If Me.DataSource.ProductNameSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(ProductsTable.ProductName)
                formattedValue = HttpUtility.HtmlEncode(formattedValue)
                If Not formattedValue is Nothing Then
                              
                    Dim maxLength as Integer = Len(formattedValue)
                    If (maxLength > CType(100, Integer)) Then
                        maxLength = CType(100, Integer)
                        
                    End If                    
                        If maxLength = CType(100, Integer) Then
                            formattedValue= NetUtils.EncodeStringForHtmlDisplay(formattedValue.SubString(0,MaxLength))
                            formattedValue = formattedValue & "..."
                            
                        End If
                    
                End If  
                            
                Me.ProductName.Text = formattedValue
              
            Else      
                Me.ProductName.Text = ProductsTable.ProductName.Format(ProductsTable.ProductName.DefaultValue)
              
            End If
                    
            If Me.ProductName.Text Is Nothing _
                OrElse Me.ProductName.Text.Trim() = "" Then
                Me.ProductName.Text = "&nbsp;"
            End If
                  
            If Me.DataSource.QuantityPerUnitSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(ProductsTable.QuantityPerUnit)
                formattedValue = HttpUtility.HtmlEncode(formattedValue)
                If Not formattedValue is Nothing Then
                              
                    Dim maxLength as Integer = Len(formattedValue)
                    If (maxLength > CType(100, Integer)) Then
                        maxLength = CType(100, Integer)
                        
                    End If                    
                        If maxLength = CType(100, Integer) Then
                            formattedValue= NetUtils.EncodeStringForHtmlDisplay(formattedValue.SubString(0,MaxLength))
                            formattedValue = formattedValue & "..."
                            
                        End If
                    
                End If  
                            
                Me.QuantityPerUnit.Text = formattedValue
              
            Else      
                Me.QuantityPerUnit.Text = ProductsTable.QuantityPerUnit.Format(ProductsTable.QuantityPerUnit.DefaultValue)
              
            End If
                    
            If Me.QuantityPerUnit.Text Is Nothing _
                OrElse Me.QuantityPerUnit.Text.Trim() = "" Then
                Me.QuantityPerUnit.Text = "&nbsp;"
            End If
                  
            If Me.DataSource.ReorderLevelSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(ProductsTable.ReorderLevel, "G")
                formattedValue = HttpUtility.HtmlEncode(formattedValue)
                If Not formattedValue is Nothing Then
                              
                    Dim maxLength as Integer = Len(formattedValue)
                    If (maxLength > CType(100, Integer)) Then
                        maxLength = CType(100, Integer)
                        
                    End If                    
                        If maxLength = CType(100, Integer) Then
                            formattedValue= NetUtils.EncodeStringForHtmlDisplay(formattedValue.SubString(0,MaxLength))
                            formattedValue = formattedValue & "..."
                            
                        End If
                    
                End If  
                            
                Me.ReorderLevel.Text = formattedValue
              
            Else      
                Me.ReorderLevel.Text = ProductsTable.ReorderLevel.Format(ProductsTable.ReorderLevel.DefaultValue, "G")
              
            End If
                    
            If Me.ReorderLevel.Text Is Nothing _
                OrElse Me.ReorderLevel.Text.Trim() = "" Then
                Me.ReorderLevel.Text = "&nbsp;"
            End If
                  
            If Me.DataSource.SupplierIDSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(ProductsTable.SupplierID)
                formattedValue = HttpUtility.HtmlEncode(formattedValue)
                If Not formattedValue is Nothing Then
                              
                    Dim maxLength as Integer = Len(formattedValue)
                    If (maxLength > CType(100, Integer)) Then
                        maxLength = CType(100, Integer)
                        
                    End If                    
                        If maxLength = CType(100, Integer) Then
                            formattedValue= NetUtils.EncodeStringForHtmlDisplay(formattedValue.SubString(0,MaxLength))
                            formattedValue = formattedValue & "..."
                            
                        End If
                    
                End If  
                            
                Me.SupplierID.Text = formattedValue
              
            Else      
                Me.SupplierID.Text = ProductsTable.SupplierID.Format(ProductsTable.SupplierID.DefaultValue)
              
            End If
                    
            If Me.SupplierID.Text Is Nothing _
                OrElse Me.SupplierID.Text.Trim() = "" Then
                Me.SupplierID.Text = "&nbsp;"
            End If
                  
            If Me.DataSource.UnitPriceSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(ProductsTable.UnitPrice, "$#,##0.00;($#,##0.00)")
                formattedValue = HttpUtility.HtmlEncode(formattedValue)
                If Not formattedValue is Nothing Then
                              
                    Dim maxLength as Integer = Len(formattedValue)
                    If (maxLength > CType(100, Integer)) Then
                        maxLength = CType(100, Integer)
                        
                    End If                    
                        If maxLength = CType(100, Integer) Then
                            formattedValue= NetUtils.EncodeStringForHtmlDisplay(formattedValue.SubString(0,MaxLength))
                            formattedValue = formattedValue & "..."
                            
                        End If
                    
                End If  
                            
                Me.UnitPrice.Text = formattedValue
              
            Else      
                Me.UnitPrice.Text = ProductsTable.UnitPrice.Format(ProductsTable.UnitPrice.DefaultValue, "$#,##0.00;($#,##0.00)")
              
            End If
                    
            If Me.UnitPrice.Text Is Nothing _
                OrElse Me.UnitPrice.Text.Trim() = "" Then
                Me.UnitPrice.Text = "&nbsp;"
            End If
                  
            If Me.DataSource.UnitsInStockSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(ProductsTable.UnitsInStock, "G")
                formattedValue = HttpUtility.HtmlEncode(formattedValue)
                If Not formattedValue is Nothing Then
                              
                    Dim maxLength as Integer = Len(formattedValue)
                    If (maxLength > CType(100, Integer)) Then
                        maxLength = CType(100, Integer)
                        
                    End If                    
                        If maxLength = CType(100, Integer) Then
                            formattedValue= NetUtils.EncodeStringForHtmlDisplay(formattedValue.SubString(0,MaxLength))
                            formattedValue = formattedValue & "..."
                            
                        End If
                    
                End If  
                            
                Me.UnitsInStock.Text = formattedValue
              
            Else      
                Me.UnitsInStock.Text = ProductsTable.UnitsInStock.Format(ProductsTable.UnitsInStock.DefaultValue, "G")
              
            End If
                    
            If Me.UnitsInStock.Text Is Nothing _
                OrElse Me.UnitsInStock.Text.Trim() = "" Then
                Me.UnitsInStock.Text = "&nbsp;"
            End If
                  
            If Me.DataSource.UnitsOnOrderSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(ProductsTable.UnitsOnOrder, "G")
                formattedValue = HttpUtility.HtmlEncode(formattedValue)
                If Not formattedValue is Nothing Then
                              
                    Dim maxLength as Integer = Len(formattedValue)
                    If (maxLength > CType(100, Integer)) Then
                        maxLength = CType(100, Integer)
                        
                    End If                    
                        If maxLength = CType(100, Integer) Then
                            formattedValue= NetUtils.EncodeStringForHtmlDisplay(formattedValue.SubString(0,MaxLength))
                            formattedValue = formattedValue & "..."
                            
                        End If
                    
                End If  
                            
                Me.UnitsOnOrder.Text = formattedValue
              
            Else      
                Me.UnitsOnOrder.Text = ProductsTable.UnitsOnOrder.Format(ProductsTable.UnitsOnOrder.DefaultValue, "G")
              
            End If
                    
            If Me.UnitsOnOrder.Text Is Nothing _
                OrElse Me.UnitsOnOrder.Text.Trim() = "" Then
                Me.UnitsOnOrder.Text = "&nbsp;"
            End If
                  
            Me.IsNewRecord = True
            If Me.DataSource.IsCreated Then
                Me.IsNewRecord = False
        
                Me.RecordUniqueId = Me.DataSource.GetID.ToXmlString()
            End If

            

            ' Load data for each record and table UI control.
            ' Ordering is important because child controls get 
            ' their parent ids from their parent UI controls.
            
      End Sub


      
        
        ' To customize, override this method in ProductsTableControlRow.
        Public Overridable Sub SaveData()

            ' 1. Load the existing record from the database. Since we save the entire record, this ensures 
            ' that fields that are not displayed also properly initialized.
            Me.LoadData()
        
            ' 2. Validate the data.  Override in ProductsTableControlRow to add custom validation.
            Me.Validate()

            ' 3. Set the values in the record with data from UI controls.  Override in ProductsTableControlRow to set additional fields.
            Me.GetUIData()

            ' 4. Save in the database.
            ' We should not save the record if the data did not change. This
            ' will save a database hit and avoid triggering any database triggers.
            If Me.DataSource.IsAnyValueChanged Then
                ' Save record to database but do not commit.
                ' Auto generated ids are available after saving for use by child (dependent) records.
                Me.DataSource.Save()
              
                DirectCast(GetParentControlObject(Me, "ProductsTableControl"), ProductsTableControl).DataChanged = True
                DirectCast(GetParentControlObject(Me, "ProductsTableControl"), ProductsTableControl).ResetData = True
            End If
            Me.DataChanged = True
            Me.ResetData = True
            ' Reseting of Me.IsNewRecord is moved to Save button's click even handler.
            ' Me.IsNewRecord() = False
            
        End Sub

        ' To customize, override this method in ProductsTableControlRow.
        Public Overridable Sub GetUIData()
            
        End Sub

        
      
        ' To customize, override this method in ProductsTableControlRow.
        Public Overridable Function CreateWhereClause() As WhereClause
        
            Return Nothing
          
        End Function
        

        ' To customize, override this method in ProductsTableControlRow.
        Public Overridable Sub Validate() 
            ' Initially empty.  Override to add custom validation.
        End Sub

        Public Overridable Sub Delete()
        
            If Me.IsNewRecord() Then
                Return
            End If

            Dim pk As KeyValue = KeyValue.XmlToKey(Me.RecordUniqueId)
            ProductsTable.DeleteRecord(pk)

          
            DirectCast(GetParentControlObject(Me, "ProductsTableControl"), ProductsTableControl).DataChanged = True
            DirectCast(GetParentControlObject(Me, "ProductsTableControl"), ProductsTableControl).ResetData = True
        End Sub

        Private Sub Control_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.PreRender
            Try
                DbUtils.StartTransaction()

                If Not Me.Page.ErrorOnPage AndAlso (Me.Page.IsPageRefresh OrElse Me.DataChanged OrElse Me.ResetData) Then
                    Me.LoadData()
                    Me.DataBind()
                End If

            Catch ex As Exception
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
                DbUtils.EndTransaction()
            End Try
        End Sub
        
        

        Protected Overrides Sub LoadViewState(ByVal savedState As Object)
            MyBase.LoadViewState(savedState)
            Dim isNewRecord As String = CType(ViewState("IsNewRecord"), String)
            If Not isNewRecord Is Nothing AndAlso isNewRecord.Trim <> "" Then
                Me.IsNewRecord = Boolean.Parse(isNewRecord)
            End If
            
            Dim myCheckSum As String = CType(ViewState("CheckSum"), String)
            If Not myCheckSum Is Nothing AndAlso myCheckSum.Trim <> "" Then
                Me.CheckSum = myCheckSum
            End If
            
        End Sub

        Protected Overrides Function SaveViewState() As Object
            ViewState("IsNewRecord") = Me.IsNewRecord.ToString()
            ViewState("CheckSum") = Me.CheckSum
            
            Return MyBase.SaveViewState()
        End Function
        
        
        ' event handler for ImageButton
        Public Overridable Sub ProductsRowCopyButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Dim url As String = "../Products/AddProductsPage.aspx?Products={PK}"
            Dim shouldRedirect As Boolean = True
            Dim TargetKey As String = Nothing
            Dim DFKA As String = Nothing
            Dim id As String = Nothing
            Dim value As String = Nothing
            Try
                DbUtils.StartTransaction
                
            url = Me.ModifyRedirectUrl(url, "",False)
            url = Me.Page.ModifyRedirectUrl(url, "",False)
                    Me.Page.CommitTransaction(sender)
          
            Catch ex As Exception
                Me.Page.RollBackTransaction(sender)
                shouldRedirect = False
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
          
            Finally
                DbUtils.EndTransaction
            End Try
            If shouldRedirect Then
                Me.Page.ShouldSaveControlsToSession = True
                Me.Page.Response.Redirect(url)
            ElseIf Not TargetKey Is Nothing AndAlso _
                        Not shouldRedirect Then
            Me.Page.ShouldSaveControlsToSession = True
            Me.Page.CloseWindow(True)
        
            End If              
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub ProductsRowDeleteButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                DbUtils.StartTransaction
                
            If(Not Me.Page.IsPageRefresh) Then
        
                  Me.Delete()
              
            End If
                Me.Page.CommitTransaction(sender)
          
            Catch ex As Exception
                Me.Page.RollBackTransaction(sender)
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
          
            Finally
                DbUtils.EndTransaction
            End Try
                  
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub ProductsRowEditButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Dim url As String = "../Products/EditProductsPage.aspx?Products={PK}"
            Dim shouldRedirect As Boolean = True
            Dim TargetKey As String = Nothing
            Dim DFKA As String = Nothing
            Dim id As String = Nothing
            Dim value As String = Nothing
            Try
                DbUtils.StartTransaction
                
            url = Me.ModifyRedirectUrl(url, "",False)
            url = Me.Page.ModifyRedirectUrl(url, "",False)
                    Me.Page.CommitTransaction(sender)
          
            Catch ex As Exception
                Me.Page.RollBackTransaction(sender)
                shouldRedirect = False
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
          
            Finally
                DbUtils.EndTransaction
            End Try
            If shouldRedirect Then
                Me.Page.ShouldSaveControlsToSession = True
                Me.Page.Response.Redirect(url)
            ElseIf Not TargetKey Is Nothing AndAlso _
                        Not shouldRedirect Then
            Me.Page.ShouldSaveControlsToSession = True
            Me.Page.CloseWindow(True)
        
            End If              
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub ProductsRowViewButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Dim url As String = "../Products/ShowProductsPage.aspx?Products={PK}"
            Dim shouldRedirect As Boolean = True
            Dim TargetKey As String = Nothing
            Dim DFKA As String = Nothing
            Dim id As String = Nothing
            Dim value As String = Nothing
            Try
                DbUtils.StartTransaction
                
            url = Me.ModifyRedirectUrl(url, "",False)
            url = Me.Page.ModifyRedirectUrl(url, "",False)
                    Me.Page.CommitTransaction(sender)
          
            Catch ex As Exception
                Me.Page.RollBackTransaction(sender)
                shouldRedirect = False
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
          
            Finally
                DbUtils.EndTransaction
            End Try
            If shouldRedirect Then
                Me.Page.ShouldSaveControlsToSession = True
                Me.Page.Response.Redirect(url)
            ElseIf Not TargetKey Is Nothing AndAlso _
                        Not shouldRedirect Then
            Me.Page.ShouldSaveControlsToSession = True
            Me.Page.CloseWindow(True)
        
            End If              
        End Sub
            
      
        Private _IsNewRecord As Boolean = True
        Public Overridable Property IsNewRecord() As Boolean
            Get
                Return Me._IsNewRecord
            End Get
            Set(ByVal value As Boolean)
                Me._IsNewRecord = value
            End Set
        End Property

        Private _DataChanged As Boolean = False
        Public Overridable Property DataChanged() As Boolean
            Get
                Return Me._DataChanged
            End Get
            Set(ByVal Value As Boolean)
                Me._DataChanged = Value
            End Set
        End Property

        Private _ResetData As Boolean = False
        Public Overridable Property ResetData() As Boolean
            Get
                Return Me._ResetData
            End Get
            Set(ByVal Value As Boolean)
                Me._ResetData = Value
            End Set
        End Property
        
        Public Property RecordUniqueId() As String
            Get
                Return CType(Me.ViewState("BaseProductsTableControlRow_Rec"), String)
            End Get
            Set(ByVal value As String)
                Me.ViewState("BaseProductsTableControlRow_Rec") = value
            End Set
        End Property
        
        Private _DataSource As ProductsRecord
        Public Property DataSource() As ProductsRecord
            Get
                Return Me._DataSource
            End Get
            Set(ByVal value As ProductsRecord)
                Me._DataSource = value
            End Set
        End Property

        Private _checkSum As String
        Public Overridable Property CheckSum() As String
            Get
                Return Me._checkSum
            End Get
            Set(ByVal value As String)
                Me._checkSum = value
            End Set
        End Property
        
        Private _TotalPages As Integer
        Public Property TotalPages() As Integer
            Get
                Return Me._TotalPages
            End Get
            Set(ByVal value As Integer)
                Me._TotalPages = value
            End Set
        End Property
        
        Private _PageIndex As Integer
        Public Property PageIndex() As Integer
            Get
                ' Return the PageIndex
                Return Me._PageIndex
            End Get
            Set(ByVal value As Integer)
                Me._PageIndex = value
            End Set
        End Property
        
        Private _DisplayLastPage As Boolean
        Public Property DisplayLastPage() As Boolean
            Get
                Return Me._DisplayLastPage
            End Get
            Set(ByVal value As Boolean)
                Me._DisplayLastPage = value
            End Set
        End Property
        
        

#Region "Helper Properties"
        
        Public ReadOnly Property CategoryID() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CategoryID"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
            
        Public ReadOnly Property Discontinued() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "Discontinued"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
            
        Public ReadOnly Property ProductName() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductName"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
            
        Public ReadOnly Property ProductsRecordRowSelection() As System.Web.UI.WebControls.CheckBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsRecordRowSelection"), System.Web.UI.WebControls.CheckBox)
            End Get
        End Property
        
        Public ReadOnly Property ProductsRowCopyButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsRowCopyButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property ProductsRowDeleteButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsRowDeleteButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property ProductsRowEditButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsRowEditButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property ProductsRowViewButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsRowViewButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property QuantityPerUnit() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "QuantityPerUnit"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
            
        Public ReadOnly Property ReorderLevel() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ReorderLevel"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
            
        Public ReadOnly Property SupplierID() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "SupplierID"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
            
        Public ReadOnly Property UnitPrice() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "UnitPrice"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
            
        Public ReadOnly Property UnitsInStock() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "UnitsInStock"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
            
        Public ReadOnly Property UnitsOnOrder() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "UnitsOnOrder"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
            
#End Region

#Region "Helper Functions"

        Public Overrides Overloads Function ModifyRedirectUrl(ByVal url As String, ByVal arg As String, ByVal bEncrypt As Boolean) As String
            Dim rec As ProductsRecord = Nothing
            
            Try
                rec = Me.GetRecord()
            Catch ex As Exception
                ' Do nothing
            End Try

            If rec Is Nothing AndAlso url.IndexOf("{") >= 0 Then
                ' Localization.
                
            Throw New Exception(Page.GetResourceValue("Err:RecDataSrcNotInitialized", "Training1"))
                    
            End If
            Return ModifyRedirectUrl(url, arg, rec, bEncrypt)
        End Function

        Public Function GetRecord() As ProductsRecord
            If Not Me.DataSource Is Nothing Then
                Return Me.DataSource
            End If
            
            If Not Me.RecordUniqueId Is Nothing Then
                Return ProductsTable.GetRecord(Me.RecordUniqueId, True)
            End If
            
            ' Localization.
            
            Throw New Exception(Page.GetResourceValue("Err:RetrieveRec", "Training1"))
                
        End Function

        Public Shadows ReadOnly Property Page() As BaseApplicationPage
            Get
                Return DirectCast(MyBase.Page, BaseApplicationPage)
            End Get
        End Property

#End Region

End Class

  

' Base class for the ProductsTableControl control on the ShowProductsTablePage page.
' Do not modify this class. Instead override any method in ProductsTableControl.
Public Class BaseProductsTableControl
        Inherits Training1.UI.BaseApplicationTableControl

        Protected Overridable Sub Control_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Init

            ' Setup the pagination events.
        
              AddHandler Me.ProductsPagination.FirstPage.Click, AddressOf ProductsPagination_FirstPage_Click
              AddHandler Me.ProductsPagination.LastPage.Click, AddressOf ProductsPagination_LastPage_Click
              AddHandler Me.ProductsPagination.NextPage.Click, AddressOf ProductsPagination_NextPage_Click
              AddHandler Me.ProductsPagination.PageSizeButton.Click, AddressOf ProductsPagination_PageSizeButton_Click
            
              AddHandler Me.ProductsPagination.PreviousPage.Click, AddressOf ProductsPagination_PreviousPage_Click

            ' Setup the sorting events.
        
              AddHandler Me.CategoryIDLabel1.Click, AddressOf CategoryIDLabel1_Click
            
              AddHandler Me.DiscontinuedLabel.Click, AddressOf DiscontinuedLabel_Click
            
              AddHandler Me.ProductNameLabel.Click, AddressOf ProductNameLabel_Click
            
              AddHandler Me.QuantityPerUnitLabel.Click, AddressOf QuantityPerUnitLabel_Click
            
              AddHandler Me.ReorderLevelLabel.Click, AddressOf ReorderLevelLabel_Click
            
              AddHandler Me.SupplierIDLabel1.Click, AddressOf SupplierIDLabel1_Click
            
              AddHandler Me.UnitPriceLabel.Click, AddressOf UnitPriceLabel_Click
            
              AddHandler Me.UnitsInStockLabel.Click, AddressOf UnitsInStockLabel_Click
            
              AddHandler Me.UnitsOnOrderLabel.Click, AddressOf UnitsOnOrderLabel_Click
            

            ' Setup the button events.
        
              AddHandler Me.ProductsCopyButton.Click, AddressOf ProductsCopyButton_Click
              AddHandler Me.ProductsDeleteButton.Click, AddressOf ProductsDeleteButton_Click
              AddHandler Me.ProductsEditButton.Click, AddressOf ProductsEditButton_Click
              AddHandler Me.ProductsExportButton.Click, AddressOf ProductsExportButton_Click
                      Me.Page.RegisterPostBackTrigger(MiscUtils.FindControlRecursively(me,"ProductsExportButton"), MiscUtils.GetParentControlObject(Me,"ProductsTableControlUpdatePanel"))
                    
              AddHandler Me.ProductsExportExcelButton.Click, AddressOf ProductsExportExcelButton_Click
                      Me.Page.RegisterPostBackTrigger(MiscUtils.FindControlRecursively(me,"ProductsExportExcelButton"), MiscUtils.GetParentControlObject(Me,"ProductsTableControlUpdatePanel"))
                    
              AddHandler Me.ProductsImportButton.Click, AddressOf ProductsImportButton_Click
              AddHandler Me.ProductsNewButton.Click, AddressOf ProductsNewButton_Click
              AddHandler Me.ProductsPDFButton.Click, AddressOf ProductsPDFButton_Click
                      Me.Page.RegisterPostBackTrigger(MiscUtils.FindControlRecursively(me,"ProductsPDFButton"), MiscUtils.GetParentControlObject(Me,"ProductsTableControlUpdatePanel"))
                    
              AddHandler Me.ProductsRefreshButton.Click, AddressOf ProductsRefreshButton_Click
              AddHandler Me.ProductsResetButton.Click, AddressOf ProductsResetButton_Click
              AddHandler Me.ProductsWordButton.Click, AddressOf ProductsWordButton_Click
                      Me.Page.RegisterPostBackTrigger(MiscUtils.FindControlRecursively(me,"ProductsWordButton"), MiscUtils.GetParentControlObject(Me,"ProductsTableControlUpdatePanel"))
                    
              AddHandler Me.MarkDiscontinued.Button.Click, AddressOf MarkDiscontinued_Click
              AddHandler Me.ProductsSearchButton.Button.Click, AddressOf ProductsSearchButton_Click
              AddHandler Me.UnmarkDiscontinued.Button.Click, AddressOf UnmarkDiscontinued_Click

            ' Setup the filter and search events.
        
            AddHandler Me.CategoryIDFilter.SelectedIndexChanged, AddressOf CategoryIDFilter_SelectedIndexChanged
            AddHandler Me.SupplierIDFilter.SelectedIndexChanged, AddressOf SupplierIDFilter_SelectedIndexChanged
            If Not Me.Page.IsPostBack AndAlso Me.InSession(Me.CategoryIDFilter) Then
                Me.CategoryIDFilter.Items.Add(New ListItem(Me.GetFromSession(Me.CategoryIDFilter), Me.GetFromSession(Me.CategoryIDFilter)))
                Me.CategoryIDFilter.SelectedValue = Me.GetFromSession(Me.CategoryIDFilter)
            End If
            If Not Me.Page.IsPostBack AndAlso Me.InSession(Me.ProductsSearchArea) Then
                
                Me.ProductsSearchArea.Text = Me.GetFromSession(Me.ProductsSearchArea)
            End If
            If Not Me.Page.IsPostBack AndAlso Me.InSession(Me.SupplierIDFilter) Then
                Me.SupplierIDFilter.Items.Add(New ListItem(Me.GetFromSession(Me.SupplierIDFilter), Me.GetFromSession(Me.SupplierIDFilter)))
                Me.SupplierIDFilter.SelectedValue = Me.GetFromSession(Me.SupplierIDFilter)
            End If

            ' Control Initializations.
            ' Initialize the table's current sort order.
            If Me.InSession(Me, "Order_By") Then
                Me.CurrentSortOrder = OrderBy.FromXmlString(Me.GetFromSession(Me, "Order_By", Nothing))
            Else
                Me.CurrentSortOrder = New OrderBy(True, True)
        
            End If

            ' Setup default pagination settings.
        
            Me.PageSize = CInt(Me.GetFromSession(Me, "Page_Size", "10"))
            Me.PageIndex = CInt(Me.GetFromSession(Me, "Page_Index", "0"))
            Me.ClearControlsFromSession()
        End Sub

        Protected Overridable Sub Control_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        
            SaveControlsToSession_Ajax()
        
                ' Show confirmation message on Click
                Me.ProductsDeleteButton.Attributes.Add("onClick", "return (confirm('" & (CType(Me.Page,BaseApplicationPage)).GetResourceValue("DeleteConfirm", "Training1") & "'));")
        End Sub

        ' Read data from database. Returns an array of records that can be assigned
        ' to the DataSource table control property.
        Public Overridable Sub LoadData()
            Try
            
                ' The WHERE clause will be empty when displaying all records in table.
                Dim wc As WhereClause = CreateWhereClause()
                If Not wc Is Nothing AndAlso Not wc.RunQuery Then
                    ' Initialize an empty array of records
                    Dim alist As New ArrayList(0)
                    Me.DataSource = DirectCast(alist.ToArray(GetType(ProductsRecord)), ProductsRecord())
                    ' Add records to the list if needed.
                    Me.AddNewRecords()
                    Return
                End If

                Dim orderBy As OrderBy = CreateOrderBy()

                ' Get the pagesize from the pagesize control.
                Me.GetPageSize()

                ' Get the total number of records to be displayed.
                Me.TotalRecords = ProductsTable.GetRecordCount(wc)

                ' Go to the last page.
                If Me.TotalPages <= 0 OrElse Me.PageIndex < 0 Then
                    Me.PageIndex = 0
                ElseIf Me.DisplayLastPage OrElse Me.PageIndex >= Me.TotalPages Then
                    Me.PageIndex = Me.TotalPages - 1
                End If

                ' Retrieve the records and set the table DataSource.
                ' Only PageSize records are fetched starting at PageIndex (zero based).
                If Me.TotalRecords <= 0 Then
                    ' Initialize an empty array of records
                    Dim alist As New ArrayList(0)
                    Me.DataSource = DirectCast(alist.ToArray(GetType(ProductsRecord)), ProductsRecord())
                ElseIf Me.AddNewRecord > 0 Then
                    ' Get the records from the posted data
                    Dim postdata As New ArrayList
                    For Each rc As ProductsTableControlRow In Me.GetRecordControls()
                        If Not rc.IsNewRecord Then
                            rc.DataSource = rc.GetRecord()
                            rc.GetUIData()
                            postdata.Add(rc.DataSource)
                        End If
                    Next
                    Me.DataSource = DirectCast(postdata.ToArray(GetType(ProductsRecord)), ProductsRecord())
                Else
                    ' Get the records from the database
                    Me.DataSource = ProductsTable.GetRecords(wc, orderBy, Me.PageIndex, Me.PageSize)
                End If
                ' Add records to the list.
                Me.AddNewRecords()

                ' Initialize the page and grand totals. now
            
            Catch ex As Exception
                Throw ex
            End Try
        End Sub

        ' Populate the UI controls.
        Public Overrides Sub DataBind()

            MyBase.DataBind()

            ' Make sure that the DataSource is initialized.
            If Me.DataSource Is Nothing Then
                Return
            End If

        
            ' Improve performance by prefetching display as records.
            Me.PreFetchForeignKeyValues()

            ' Setup the pagination controls.
            BindPaginationControls()

            ' Populate all filters data.
        
            Me.PopulateCategoryIDFilter(GetSelectedValue(Me.CategoryIDFilter, Me.GetFromSession(Me.CategoryIDFilter)), 500)
                    
            Me.PopulateSupplierIDFilter(GetSelectedValue(Me.SupplierIDFilter, Me.GetFromSession(Me.SupplierIDFilter)), 500)
                    

            ' Bind the repeater with the list of records to expand the UI.
            Dim rep As System.Web.UI.WebControls.Repeater = CType(Me.FindControl("ProductsTableControlRepeater"), System.Web.UI.WebControls.Repeater)
            rep.DataSource = Me.DataSource()
            rep.DataBind()

            Dim index As Integer = 0
            Dim repItem As System.Web.UI.WebControls.RepeaterItem
            For Each repItem In rep.Items
                ' Loop through all rows in the table, set its DataSource and call DataBind().
                Dim recControl As ProductsTableControlRow = DirectCast(repItem.FindControl("ProductsTableControlRow"), ProductsTableControlRow)
                recControl.DataSource = Me.DataSource(index)
                recControl.DataBind()
                recControl.Visible = Not Me.InDeletedRecordIds(recControl)
                index += 1
            Next
        End Sub

        
        Public Sub PreFetchForeignKeyValues()
            If Me.DataSource Is Nothing Then
                Return
            End If
          
            Me.Page.PregetDfkaRecords(ProductsTable.CategoryID, Me.DataSource)
            Me.Page.PregetDfkaRecords(ProductsTable.SupplierID, Me.DataSource)
        End Sub
         

        Protected Overridable Sub BindPaginationControls()

            ' Setup the pagination controls.

            ' Bind the buttons for ProductsTableControl pagination.
        
            Me.ProductsPagination.FirstPage.Enabled = Not (Me.PageIndex = 0)
            Me.ProductsPagination.LastPage.Enabled = Not (Me.PageIndex = Me.TotalPages - 1)
            If Me.TotalPages = 0 Then
                Me.ProductsPagination.LastPage.Enabled = False
            End If
          
            Me.ProductsPagination.NextPage.Enabled = Not (Me.PageIndex = Me.TotalPages - 1)
            If Me.TotalPages = 0 Then
                Me.ProductsPagination.NextPage.Enabled = False
            End If
          
            Me.ProductsPagination.PreviousPage.Enabled = Not (Me.PageIndex = 0)

            ' Bind the pagination labels.
        
            If Me.TotalPages > 0 Then
                Me.ProductsPagination.CurrentPage.Text = (Me.PageIndex + 1).ToString()
            Else
                Me.ProductsPagination.CurrentPage.Text = "0"
            End If
            Me.ProductsPagination.PageSize.Text = Me.PageSize.ToString()
            Me.ProductsTotalItems.Text = Me.TotalRecords.ToString()
            Me.ProductsPagination.TotalItems.Text = Me.TotalRecords.ToString()
            Me.ProductsPagination.TotalPages.Text = Me.TotalPages.ToString()
        End Sub

        Public Overridable Sub SaveData()
            Dim recCtl As ProductsTableControlRow
            For Each recCtl In Me.GetRecordControls()
        
                If Me.InDeletedRecordIds(recCtl) Then
                    recCtl.Delete()
                Else
                    If recCtl.Visible Then
                        recCtl.SaveData()
                    End If
                End If
          
            Next
            
            Me.DataChanged = True
            Me.ResetData = True
        End Sub

        Public Overridable Function CreateOrderBy() As OrderBy
            Return Me.CurrentSortOrder
        End Function
        
        'This CreateWhereClause is used for loading the data.
        Public Overridable Function CreateWhereClause() As WhereClause
            ProductsTable.Instance.InnerFilter = Nothing
            Dim wc As WhereClause = New WhereClause()
            ' Compose the WHERE clause consiting of:
            ' 1. Static clause defined at design time.
            ' 2. User selected filter criteria.
            ' 3. User selected search criteria.
        
            If IsValueSelected(Me.CategoryIDFilter) Then
                
                wc.iAND(ProductsTable.CategoryID, BaseFilter.ComparisonOperator.EqualsTo, MiscUtils.GetSelectedValue(Me.CategoryIDFilter, Me.GetFromSession(Me.CategoryIDFilter)), False, False)
                    
                
            End If
                       
            If IsValueSelected(Me.ProductsSearchArea) Then
                ' Strip "..." from begin and ending of the search text, otherwise the search will return 0 values as in database "..." is not stored.
                If Me.ProductsSearchArea.Text.StartsWith("...") then
                    Me.ProductsSearchArea.Text = Me.ProductsSearchArea.Text.SubString(3,Me.ProductsSearchArea.Text.Length-3)
                End If
                If Me.ProductsSearchArea.Text.EndsWith("...") then
                    Me.ProductsSearchArea.Text = Me.ProductsSearchArea.Text.SubString(0,Me.ProductsSearchArea.Text.Length-3)
                End If
                ' After stripping "..." see if the search text is null or empty.
                If IsValueSelected(Me.ProductsSearchArea) Then
                      
                    ' These clauses are added depending on operator and fields selected in Control's property page, bindings tab.
                    Dim search As WhereClause = New WhereClause()
                    
                    search.iOR(ProductsTable.ProductName, BaseFilter.ComparisonOperator.Contains, MiscUtils.GetSelectedValue(Me.ProductsSearchArea, Me.GetFromSession(Me.ProductsSearchArea)), True, False)
        
                    search.iOR(ProductsTable.SupplierID, BaseFilter.ComparisonOperator.Contains, MiscUtils.GetSelectedValue(Me.ProductsSearchArea, Me.GetFromSession(Me.ProductsSearchArea)), True, False)
        
                    search.iOR(ProductsTable.CategoryID, BaseFilter.ComparisonOperator.Contains, MiscUtils.GetSelectedValue(Me.ProductsSearchArea, Me.GetFromSession(Me.ProductsSearchArea)), True, False)
        
                    wc.iAND(search)
                End If
            End If
                  
            If IsValueSelected(Me.SupplierIDFilter) Then
                
                wc.iAND(ProductsTable.SupplierID, BaseFilter.ComparisonOperator.EqualsTo, MiscUtils.GetSelectedValue(Me.SupplierIDFilter, Me.GetFromSession(Me.SupplierIDFilter)), False, False)
                    
                
            End If
                       
            Return wc
        End Function
        
        
        ' This CreateWhereClause is used for loading list of suggestions for Auto Type-Ahead feature.
        Public Overridable Function CreateWhereClause(ByVal searchText as String, ByVal fromSearchControl as String, ByVal AutoTypeAheadSearch as String, ByVal AutoTypeAheadWordSeparators as String) As WhereClause
            ProductsTable.Instance.InnerFilter = Nothing
            Dim wc As WhereClause = New WhereClause()
            ' Compose the WHERE clause consiting of:
            ' 1. Static clause defined at design time.
            ' 2. User selected filter criteria.
            ' 3. User selected search criteria.
            Dim appRelativeVirtualPath As String = CType(HttpContext.Current.Session("AppRelatvieVirtualPath"), String)
          
            ' Adds clauses if values are selected in Filter controls which are configured in the page.
          
            Dim CategoryIDFilterSelectedValue As String = CType(HttpContext.Current.Session()(HttpContext.Current.Session.SessionID & appRelativeVirtualPath & "CategoryIDFilter_Ajax"), String)
            If IsValueSelected(CategoryIDFilterSelectedValue) Then
                wc.iAND(ProductsTable.CategoryID, BaseFilter.ComparisonOperator.EqualsTo, CategoryIDFilterSelectedValue, False, False)
            End If
                      
            If IsValueSelected(searchText) and fromSearchControl = "ProductsSearchArea" Then
                Dim formatedSearchText as String = searchText
                ' strip "..." from begin and ending of the search text, otherwise the search will return 0 values as in database "..." is not stored.
                If searchText.StartsWith("...") then
                    formatedSearchText = searchText.SubString(3,searchText.Length-3)
                End If
                If searchText.EndsWith("...") then
                    formatedSearchText = searchText.SubString(0,searchText.Length-3)
                End If
                'After stripping "...", trim any leading and trailing whitespaces 
                formatedSearchText = formatedSearchText.Trim()
                ' After stripping "..." see if the search text is null or empty.
                If IsValueSelected(formatedSearchText) Then
                      
                    ' These clauses are added depending on operator and fields selected in Control's property page, bindings tab.
                    Dim search As WhereClause = New WhereClause()
                    
                    If InvariantLCase(AutoTypeAheadSearch).equals("wordsstartingwithsearchstring") Then
                
                        search.iOR(ProductsTable.ProductName, BaseFilter.ComparisonOperator.Starts_With, formatedSearchText, True, False)
                        search.iOR(ProductsTable.ProductName, BaseFilter.ComparisonOperator.Contains, AutoTypeAheadWordSeparators & formatedSearchText, True, False)
                
                        search.iOR(ProductsTable.SupplierID, BaseFilter.ComparisonOperator.Starts_With, formatedSearchText, True, False)
                        search.iOR(ProductsTable.SupplierID, BaseFilter.ComparisonOperator.Contains, AutoTypeAheadWordSeparators & formatedSearchText, True, False)
                
                        search.iOR(ProductsTable.CategoryID, BaseFilter.ComparisonOperator.Starts_With, formatedSearchText, True, False)
                        search.iOR(ProductsTable.CategoryID, BaseFilter.ComparisonOperator.Contains, AutoTypeAheadWordSeparators & formatedSearchText, True, False)
                
                    Else
                        
                        search.iOR(ProductsTable.ProductName, BaseFilter.ComparisonOperator.Contains, formatedSearchText, True, False)
                        search.iOR(ProductsTable.SupplierID, BaseFilter.ComparisonOperator.Contains, formatedSearchText, True, False)
                        search.iOR(ProductsTable.CategoryID, BaseFilter.ComparisonOperator.Contains, formatedSearchText, True, False)
                    End If
                    wc.iAND(search)
                End If
            End If
                  
            Dim SupplierIDFilterSelectedValue As String = CType(HttpContext.Current.Session()(HttpContext.Current.Session.SessionID & appRelativeVirtualPath & "SupplierIDFilter_Ajax"), String)
            If IsValueSelected(SupplierIDFilterSelectedValue) Then
                wc.iAND(ProductsTable.SupplierID, BaseFilter.ComparisonOperator.EqualsTo, SupplierIDFilterSelectedValue, False, False)
            End If
                      
            Return wc
        End Function
          
        Public Overridable Function GetAutoCompletionList_ProductsSearchArea(ByVal prefixText As String, ByVal count As Integer) As String()
            Dim resultList As ArrayList = New ArrayList
            Dim wordList As ArrayList = New ArrayList
            Dim iteration As Integer = 0
            
            Dim wc As WhereClause = CreateWhereClause(prefixText,"ProductsSearchArea", "WordsStartingWithSearchString", "[!a-zA-Z0-9]")
            While (resultList.Count < count AndAlso iteration < 5)
                ' Fetch 100 records in each iteration
                Dim records() As Training1.Business.ProductsRecord = ProductsTable.GetRecords(wc, Nothing, iteration, 100)
                Dim rec As ProductsRecord = Nothing
                Dim resultItem As String = ""
                For Each rec In records
                    ' Exit the loop if recordList count has reached AutoTypeAheadListSize.
                    If resultList.Count >= count then
                        Exit For
                    End If
                    ' If the field is configured to Display as Foreign key, Format() method returns the 
                    ' Display as Forien Key value instead of original field value.
                    ' Since search had to be done in multiple fields (selected in Control's page property, binding tab) in a record,
                    ' We need to find relevent field to display which matches the prefixText and is not already present in the result list.
                
                    resultItem = rec.Format(ProductsTable.ProductName)
                    If InvariantUCase(resultItem).Contains(InvariantUCase(prefixText))  Then
                        Dim isAdded as Boolean = FormatSuggestions(prefixText, resultItem, 50, "AtBeginningOfMatchedString", "WordsStartingWithSearchString", "[^a-zA-Z0-9]", resultList)
                        If isAdded Then
                            Continue For
                        End If
                    End If
      
                    resultItem = rec.Format(ProductsTable.SupplierID)
                    If InvariantUCase(resultItem).Contains(InvariantUCase(prefixText))  Then
                        Dim isAdded as Boolean = FormatSuggestions(prefixText, resultItem, 50, "AtBeginningOfMatchedString", "WordsStartingWithSearchString", "[^a-zA-Z0-9]", resultList)
                        If isAdded Then
                            Continue For
                        End If
                    End If
      
                    resultItem = rec.Format(ProductsTable.CategoryID)
                    If InvariantUCase(resultItem).Contains(InvariantUCase(prefixText))  Then
                        Dim isAdded as Boolean = FormatSuggestions(prefixText, resultItem, 50, "AtBeginningOfMatchedString", "WordsStartingWithSearchString", "[^a-zA-Z0-9]", resultList)
                        If isAdded Then
                            Continue For
                        End If
                    End If
      
                Next
                ' Exit the loop if number of records found is less as further iteration will not return any more records
                If records.Length < 100 Then
                    Exit While
                End If
                iteration += 1
            End While
            resultList.Sort()
            Dim result() As String = New String(resultList.Count - 1) {}
            Array.Copy(resultList.ToArray, result, resultList.Count)
            Return result
        End Function
          
          
        'Formats the resultItem and adds it to the list of suggestions.
        Public Overridable Function FormatSuggestions(ByVal prefixText As String, ByVal resultItem as String, _
                                                 ByVal columnLength As Integer, ByVal AutoTypeAheadDisplayFoundText as String, _
                                                 ByVal autoTypeAheadSearch as String, ByVal AutoTypeAheadWordSeparators as String, _
                                                 ByVal resultList as ArrayList) as Boolean
            Dim index As Integer = InvariantLCase(resultItem).IndexOf(InvariantLCase(prefixText))
            Dim itemToAdd As String = ""
            Dim isFound as Boolean = False
            Dim isAdded as Boolean = False
            ' Get the index where prfixt is at the beginning of resultItem. If not found then, index of word which begins with prefixText.
            If InvariantLCase(autoTypeAheadSearch).equals("wordsstartingwithsearchstring") and not index = 0 Then
                ' Expression to find word which contains AutoTypeAheadWordSeparators followed by prefixText
                Dim regex1 As System.Text.RegularExpressions.Regex = new System.Text.RegularExpressions.Regex( AutoTypeAheadWordSeparators + prefixText, System.Text.RegularExpressions.RegexOptions.IgnoreCase)
                If regex1.IsMatch(resultItem) Then
                    index = regex1.Match(resultItem).Index
                    isFound = True
                End If
                ' If the prefixText is found immediatly after white space then starting of the word is found so don not search any further
                If not resultItem(index).ToString() = " " Then
                    ' Expression to find beginning of the word which contains AutoTypeAheadWordSeparators followed by prefixText
                    Dim regex As System.Text.RegularExpressions.Regex = new System.Text.RegularExpressions.Regex("\\S*" + AutoTypeAheadWordSeparators + prefixText, System.Text.RegularExpressions.RegexOptions.IgnoreCase)
                    If regex.IsMatch(resultItem) Then
                        index = regex.Match(resultItem).Index
                        isFound = True
                    End If
                 End If
            End If
            ' If autoTypeAheadSearch value is wordsstartingwithsearchstring then, extract the substring only if the prefixText is found at the 
            ' beginning of the resultItem (index = 0) or a word in resultItem is found starts with prefixText. 
            If index = 0 Or isFound Or InvariantLCase(autoTypeAheadSearch).Equals("anywhereinstring") then
                If InvariantLCase(AutoTypeAheadDisplayFoundText).equals("atbeginningofmatchedstring") Then
                    ' Expression to find beginning of the word which contains prefixText
                    Dim regex1 As System.Text.RegularExpressions.Regex = new System.Text.RegularExpressions.Regex("\\S*" + prefixText, System.Text.RegularExpressions.RegexOptions.IgnoreCase)
                    '  Find the beginning of the word which contains prefexText
                    If (StringUtils.InvariantLCase(autoTypeAheadSearch).Equals("anywhereinstring") AndAlso regex1.IsMatch(resultItem)) Then
                        index = regex1.Match(resultItem).Index
                        isFound = True
                    End If
                    ' Display string from the index till end of the string if sub string from index till end is less than columnLength value.
                    If Len(resultItem) - index <= columnLength Then
                        If index = 0 Then 
                            itemToAdd = resultItem 
                        Else
                            itemToAdd = "..." & resultItem.Substring(index, Len(resultItem) - index) 
                        End If
                    Else
                        If index = 0 Then
                            itemToAdd = resultItem.Substring(index, (columnLength - 3)) & "..."
                        Else
                            'Truncate the string to show only columnLength - 6 characters as begining and trailing "..." has to be appended.
                            itemToAdd = "..." & resultItem.Substring(index , columnLength - 6) & "..." 
                        End If
                    End If
                ElseIf InvariantLCase(AutoTypeAheadDisplayFoundText).equals("inmiddleofmatchedstring") Then
                    Dim subStringBeginIndex as Integer = CType(columnLength/2, Integer)
                    If Len(resultItem) <= columnLength Then
                        itemToAdd = resultItem
                    Else
                        ' Sanity check at end of the string
                        If index + Len(prefixText) = columnLength Then
                            itemToAdd =  "..." & resultItem.Substring(index-columnLength,index)
                        ElseIf Len(resultITem) - index < subStringBeginIndex Then 
                            ' Display string from the end till columnLength value if, index is closer to the end of the string.
                            itemToAdd =  "..." & resultItem.Substring(Len(resultItem)-columnLength,Len(resultItem))
                        ElseIf index <= subStringBeginIndex Then 
                            ' Sanity chet at beginning of the string
                            itemToAdd =  resultItem.Substring(0, columnLength) & "..."
                        Else
                            ' Display string containing text before the prefixText occures and text after the prefixText
                            itemToAdd =  "..." & resultItem.Substring(index - subStringBeginIndex, columnLength) & "..." 
                        End If
                    End If
                ElseIf InvariantLCase(AutoTypeAheadDisplayFoundText).equals("atendofmatchedstring") Then
                     ' Expression to find ending of the word which contains prefexText
                    Dim regex1 as System.Text.RegularExpressions.Regex = new System.Text.RegularExpressions.Regex("\s", System.Text.RegularExpressions.RegexOptions.IgnoreCase)
                    ' Find the ending of the word which contains prefexText
                    If regex1.IsMatch(resultItem, index + 1) Then
                        index = regex1.Match(resultItem, index + 1).Index
                    Else
                        ' If the word which contains prefexText is the last word in string, regex1.IsMatch returns false.
                        index = resultItem.Length
                    End If
                    If index > Len(resultItem) Then
                        index = Len(resultItem)
                    End If
                    ' If text from beginning of the string till index is less than columnLength value then, display string from the beginning till index.
                    If  index <= columnLength Then
                        if index = Len(resultItem) then   'Make decision to append "..."
                            itemToAdd = resultItem.Substring(0,index)
                        Else
                            itemToAdd = resultItem.Substring(0,index) & "..."
                        End If
                    Else
                        If index = Len(resultItem) Then
                            itemToAdd = "..." & resultItem.Substring(index - (columnLength - 3), (columnLength - 3))
                        Else
                            'Truncate the string to show only columnLength - 6 characters as begining and trailing "..." has to be appended.
                            itemToAdd = "..." & resultItem.Substring(index - (columnLength - 6), columnLength - 6) & "..." 
                        End If
                    End If
                End If
                
                ' Remove newline character from itemToAdd
                Dim prefixTextIndex As Integer = itemToAdd.IndexOf(prefixText, StringComparison.InvariantCultureIgnoreCase)
                ' If itemToAdd contains any newline after the search text then show text only till newline
                Dim regex2 As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("(" & vbCrLf & "|" & vbLf & ")", System.Text.RegularExpressions.RegexOptions.IgnoreCase)
                Dim newLineIndexAfterPrefix As Integer = -1
                If regex2.IsMatch(itemToAdd, prefixTextIndex) Then
                    newLineIndexAfterPrefix = regex2.Match(itemToAdd, prefixTextIndex).Index
                End If
                If (newLineIndexAfterPrefix > -1) Then
                    If itemToAdd.EndsWith("...") Then
                        itemToAdd = (itemToAdd.Substring(0, newLineIndexAfterPrefix) + "...")
                    Else
                        itemToAdd = itemToAdd.Substring(0, newLineIndexAfterPrefix)
                    End If
                End If
                ' If itemToAdd contains any newline before search text then show text which comes after newline
                Dim regex3 As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("(" & vbCrLf & "|" & vbLf & ")", (System.Text.RegularExpressions.RegexOptions.IgnoreCase Or System.Text.RegularExpressions.RegexOptions.RightToLeft))
                Dim newLineIndexBeforePrefix As Integer = -1
                If regex3.IsMatch(itemToAdd, prefixTextIndex) Then
                    newLineIndexBeforePrefix = regex3.Match(itemToAdd, prefixTextIndex).Index
                End If
                If (newLineIndexBeforePrefix > -1) Then
                    If itemToAdd.StartsWith("...") Then
                        itemToAdd = ("..." + itemToAdd.Substring((newLineIndexBeforePrefix + regex3.Match(itemToAdd, prefixTextIndex).Length)))
                    Else
                        itemToAdd = itemToAdd.Substring((newLineIndexBeforePrefix + regex3.Match(itemToAdd, prefixTextIndex).Length))
                    End If
                End If

                If Not itemToAdd is nothing AndAlso Not resultList.Contains(itemToAdd) Then
                    resultList.Add(itemToAdd)
                    isAdded = true
                End If
            End If
            Return isAdded
        End Function
        
    
        Protected Overridable Sub GetPageSize()
        
            If Me.ProductsPagination.PageSize.Text.Trim <> "" Then
                Try
                    'Me.PageSize = Integer.Parse(Me.ProductsPagination.PageSize.Text)
                Catch ex As Exception
                End Try
            End If
        End Sub

        Protected Overridable Sub AddNewRecords()
            Dim newRecordList As ArrayList = New ArrayList()

            ' Loop though all the record controls and if the record control
            ' does not have a unique record id set, then create a record
            ' and add to the list.
            If Not Me.ResetData Then
                Dim rep As System.Web.UI.WebControls.Repeater = CType(Me.FindControl("ProductsTableControlRepeater"), System.Web.UI.WebControls.Repeater)

                Dim repItem As System.Web.UI.WebControls.RepeaterItem
                For Each repItem In rep.Items
                    ' Loop through all rows in the table, set its DataSource and call DataBind().
                    Dim recControl As ProductsTableControlRow = DirectCast(repItem.FindControl("ProductsTableControlRow"), ProductsTableControlRow)

                    If recControl.Visible AndAlso recControl.IsNewRecord() Then
                        Dim rec As ProductsRecord = New ProductsRecord()
        
                        If recControl.CategoryID.Text <> "" Then
                            rec.Parse(recControl.CategoryID.Text, ProductsTable.CategoryID)
                        End If
                        If recControl.Discontinued.Text <> "" Then
                            rec.Parse(recControl.Discontinued.Text, ProductsTable.Discontinued)
                        End If
                        If recControl.ProductName.Text <> "" Then
                            rec.Parse(recControl.ProductName.Text, ProductsTable.ProductName)
                        End If
                        If recControl.QuantityPerUnit.Text <> "" Then
                            rec.Parse(recControl.QuantityPerUnit.Text, ProductsTable.QuantityPerUnit)
                        End If
                        If recControl.ReorderLevel.Text <> "" Then
                            rec.Parse(recControl.ReorderLevel.Text, ProductsTable.ReorderLevel)
                        End If
                        If recControl.SupplierID.Text <> "" Then
                            rec.Parse(recControl.SupplierID.Text, ProductsTable.SupplierID)
                        End If
                        If recControl.UnitPrice.Text <> "" Then
                            rec.Parse(recControl.UnitPrice.Text, ProductsTable.UnitPrice)
                        End If
                        If recControl.UnitsInStock.Text <> "" Then
                            rec.Parse(recControl.UnitsInStock.Text, ProductsTable.UnitsInStock)
                        End If
                        If recControl.UnitsOnOrder.Text <> "" Then
                            rec.Parse(recControl.UnitsOnOrder.Text, ProductsTable.UnitsOnOrder)
                        End If
                        newRecordList.Add(rec)
                    End If
                Next
            End If

            ' Add any new record to the list.
            Dim index As Integer = 0
            For index = 1 To Me.AddNewRecord
                newRecordList.Insert(0, New ProductsRecord())
            Next
            Me.AddNewRecord = 0

            ' Finally, add any new records to the DataSource.
            If newRecordList.Count > 0 Then
                Dim finalList As ArrayList = New ArrayList(Me.DataSource)
                finalList.InsertRange(0, newRecordList)

                Me.DataSource = DirectCast(finalList.ToArray(GetType(ProductsRecord)), ProductsRecord())
            End If

        End Sub

        
        Public Sub AddToDeletedRecordIds(ByVal rec As ProductsTableControlRow)
            If rec.IsNewRecord() Then
                Return
            End If

            If Not Me.DeletedRecordIds Is Nothing AndAlso Me.DeletedRecordIds.Trim <> "" Then
                Me.DeletedRecordIds &= ","
            End If

            Me.DeletedRecordIds &= "[" & rec.RecordUniqueId & "]"
        End Sub

        Private Function InDeletedRecordIds(ByVal rec As ProductsTableControlRow) As Boolean
            If Me.DeletedRecordIds Is Nothing OrElse Me.DeletedRecordIds.Trim = "" Then
                Return False
            End If

            Return Me.DeletedRecordIds.IndexOf("[" & rec.RecordUniqueId & "]") >= 0
        End Function

        Private _DeletedRecordIds As String
        Public Property DeletedRecordIds() As String
            Get
                Return Me._DeletedRecordIds
            End Get

            Set(ByVal value As String)
                Me._DeletedRecordIds = value
            End Set
        End Property
        
        ' Get the filters' data for CategoryIDFilter
        Protected Overridable Sub PopulateCategoryIDFilter(ByVal selectedValue As String, ByVal maxItems As Integer)
                    
            'Setup the WHERE clause.
            Dim wc As WhereClause = New WhereClause
            Dim orderBy As OrderBy = New OrderBy(False, True)
            orderBy.Add(CategoriesTable.CategoryName, OrderByItem.OrderDir.Asc)

            Dim noValueFormat As String = GetValueFromResourceFile("Txt:Other", "Training1")

            Me.CategoryIDFilter.Items.Clear()
            Dim itemValue As CategoriesRecord
            For Each itemValue In CategoriesTable.GetRecords(wc, orderBy, 0, maxItems)
                ' Create the item and add to the list.
                Dim cvalue As String = Nothing
                Dim fvalue As String = noValueFormat
                If itemValue.CategoryIDSpecified Then
                    cvalue = itemValue.CategoryID.ToString()
                    fvalue = itemValue.Format(CategoriesTable.CategoryName)
                End If

                Dim item As ListItem = New ListItem(fvalue, cvalue)
                If Me.CategoryIDFilter.Items.IndexOf(item) < 0 Then
                    Me.CategoryIDFilter.Items.Add(item)
                End If
            Next
                
            ' Set the selected value.
            SetSelectedValue(Me.CategoryIDFilter, selectedValue)

            ' Add the All item.
            Me.CategoryIDFilter.Items.Insert(0, New ListItem(Page.GetResourceValue("Txt:All", "Training1"), "--ANY--"))

                
        End Sub
            
        ' Get the filters' data for SupplierIDFilter
        Protected Overridable Sub PopulateSupplierIDFilter(ByVal selectedValue As String, ByVal maxItems As Integer)
                    
            'Setup the WHERE clause.
            Dim wc As WhereClause = New WhereClause
            Dim orderBy As OrderBy = New OrderBy(False, True)
            orderBy.Add(SuppliersTable.CompanyName, OrderByItem.OrderDir.Asc)

            Dim noValueFormat As String = GetValueFromResourceFile("Txt:Other", "Training1")

            Me.SupplierIDFilter.Items.Clear()
            Dim itemValue As SuppliersRecord
            For Each itemValue In SuppliersTable.GetRecords(wc, orderBy, 0, maxItems)
                ' Create the item and add to the list.
                Dim cvalue As String = Nothing
                Dim fvalue As String = noValueFormat
                If itemValue.SupplierIDSpecified Then
                    cvalue = itemValue.SupplierID.ToString()
                    fvalue = itemValue.Format(SuppliersTable.CompanyName)
                End If

                Dim item As ListItem = New ListItem(fvalue, cvalue)
                If Me.SupplierIDFilter.Items.IndexOf(item) < 0 Then
                    Me.SupplierIDFilter.Items.Add(item)
                End If
            Next
                
            ' Set the selected value.
            SetSelectedValue(Me.SupplierIDFilter, selectedValue)

            ' Add the All item.
            Me.SupplierIDFilter.Items.Insert(0, New ListItem(Page.GetResourceValue("Txt:All", "Training1"), "--ANY--"))

                
        End Sub
            
        ' Create a where clause for the filter CategoryIDFilter.
        Public Overridable Function CreateWhereClause_CategoryIDFilter() As WhereClause
              
            Dim wc As WhereClause = New WhereClause()
                  
            If IsValueSelected(Me.ProductsSearchArea) Then
                ' Strip "..." from begin and ending of the search text, otherwise the search will return 0 values as in database "..." is not stored.
                If Me.ProductsSearchArea.Text.StartsWith("...") then
                    Me.ProductsSearchArea.Text = Me.ProductsSearchArea.Text.SubString(3,Me.ProductsSearchArea.Text.Length-3)
                End If
                If Me.ProductsSearchArea.Text.EndsWith("...") then
                    Me.ProductsSearchArea.Text = Me.ProductsSearchArea.Text.SubString(0,Me.ProductsSearchArea.Text.Length-3)
                End If
                ' After stripping "..." see if the search text is null or empty.
                If IsValueSelected(Me.ProductsSearchArea) Then
                      
                    ' These clauses are added depending on operator and fields selected in Control's property page, bindings tab.
                    Dim search As WhereClause = New WhereClause()
                    
                    search.iOR(ProductsTable.ProductName, BaseFilter.ComparisonOperator.Contains, MiscUtils.GetSelectedValue(Me.ProductsSearchArea, Me.GetFromSession(Me.ProductsSearchArea)), True, False)
        
                    search.iOR(ProductsTable.SupplierID, BaseFilter.ComparisonOperator.Contains, MiscUtils.GetSelectedValue(Me.ProductsSearchArea, Me.GetFromSession(Me.ProductsSearchArea)), True, False)
        
                    search.iOR(ProductsTable.CategoryID, BaseFilter.ComparisonOperator.Contains, MiscUtils.GetSelectedValue(Me.ProductsSearchArea, Me.GetFromSession(Me.ProductsSearchArea)), True, False)
        
                    wc.iAND(search)
                End If
            End If
                  
            If IsValueSelected(Me.SupplierIDFilter) Then
                
                wc.iAND(ProductsTable.SupplierID, BaseFilter.ComparisonOperator.EqualsTo, MiscUtils.GetSelectedValue(Me.SupplierIDFilter, Me.GetFromSession(Me.SupplierIDFilter)), False, False)
                    
                
            End If
                       
            Return wc
        End Function
            
        ' Create a where clause for the filter ProductsSearchArea.
        Public Overridable Function CreateWhereClause_ProductsSearchArea() As WhereClause
              
            Dim wc As WhereClause = New WhereClause()
                  
            If IsValueSelected(Me.CategoryIDFilter) Then
                
                wc.iAND(ProductsTable.CategoryID, BaseFilter.ComparisonOperator.EqualsTo, MiscUtils.GetSelectedValue(Me.CategoryIDFilter, Me.GetFromSession(Me.CategoryIDFilter)), False, False)
                    
                
            End If
                       
            If IsValueSelected(Me.SupplierIDFilter) Then
                
                wc.iAND(ProductsTable.SupplierID, BaseFilter.ComparisonOperator.EqualsTo, MiscUtils.GetSelectedValue(Me.SupplierIDFilter, Me.GetFromSession(Me.SupplierIDFilter)), False, False)
                    
                
            End If
                       
            Return wc
        End Function
            
        ' Create a where clause for the filter SupplierIDFilter.
        Public Overridable Function CreateWhereClause_SupplierIDFilter() As WhereClause
              
            Dim wc As WhereClause = New WhereClause()
                  
            If IsValueSelected(Me.CategoryIDFilter) Then
                
                wc.iAND(ProductsTable.CategoryID, BaseFilter.ComparisonOperator.EqualsTo, MiscUtils.GetSelectedValue(Me.CategoryIDFilter, Me.GetFromSession(Me.CategoryIDFilter)), False, False)
                    
                
            End If
                       
            If IsValueSelected(Me.ProductsSearchArea) Then
                ' Strip "..." from begin and ending of the search text, otherwise the search will return 0 values as in database "..." is not stored.
                If Me.ProductsSearchArea.Text.StartsWith("...") then
                    Me.ProductsSearchArea.Text = Me.ProductsSearchArea.Text.SubString(3,Me.ProductsSearchArea.Text.Length-3)
                End If
                If Me.ProductsSearchArea.Text.EndsWith("...") then
                    Me.ProductsSearchArea.Text = Me.ProductsSearchArea.Text.SubString(0,Me.ProductsSearchArea.Text.Length-3)
                End If
                ' After stripping "..." see if the search text is null or empty.
                If IsValueSelected(Me.ProductsSearchArea) Then
                      
                    ' These clauses are added depending on operator and fields selected in Control's property page, bindings tab.
                    Dim search As WhereClause = New WhereClause()
                    
                    search.iOR(ProductsTable.ProductName, BaseFilter.ComparisonOperator.Contains, MiscUtils.GetSelectedValue(Me.ProductsSearchArea, Me.GetFromSession(Me.ProductsSearchArea)), True, False)
        
                    search.iOR(ProductsTable.SupplierID, BaseFilter.ComparisonOperator.Contains, MiscUtils.GetSelectedValue(Me.ProductsSearchArea, Me.GetFromSession(Me.ProductsSearchArea)), True, False)
        
                    search.iOR(ProductsTable.CategoryID, BaseFilter.ComparisonOperator.Contains, MiscUtils.GetSelectedValue(Me.ProductsSearchArea, Me.GetFromSession(Me.ProductsSearchArea)), True, False)
        
                    wc.iAND(search)
                End If
            End If
                  
            Return wc
        End Function
            
        Private Sub Control_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.PreRender
            Try
                DbUtils.StartTransaction
                
                If Not Me.Page.ErrorOnPage AndAlso (Me.Page.IsPageRefresh OrElse Me.DataChanged OrElse Me.ResetData) Then
                    Me.LoadData()
                    Me.DataBind()
                End If
                
            Catch ex As Exception
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
                DbUtils.EndTransaction
            End Try
        End Sub
        
        Protected Overrides Sub SaveControlsToSession()
            MyBase.SaveControlsToSession()

            ' Save filter controls to values to session.
        
            Me.SaveToSession(Me.CategoryIDFilter, Me.CategoryIDFilter.SelectedValue)
                  
            Me.SaveToSession(Me.ProductsSearchArea, Me.ProductsSearchArea.Text)
                  
            Me.SaveToSession(Me.SupplierIDFilter, Me.SupplierIDFilter.SelectedValue)
                  
            
            ' Save table control properties to the session.
            If Not Me.CurrentSortOrder Is Nothing Then
                Me.SaveToSession(Me, "Order_By", Me.CurrentSortOrder.ToXmlString())
            End If
            Me.SaveToSession(Me, "Page_Index", Me.PageIndex.ToString())
            Me.SaveToSession(Me, "Page_Size", Me.PageSize.ToString())
        
            Me.SaveToSession(Me, "DeletedRecordIds", Me.DeletedRecordIds)  
        
        End Sub
        
        Protected  Sub SaveControlsToSession_Ajax()
            ' Save filter controls to values to session.
          
            Me.SaveToSession("CategoryIDFilter_Ajax", Me.CategoryIDFilter.SelectedValue)
            Me.SaveToSession("ProductsSearchArea_Ajax", Me.ProductsSearchArea.Text)
            Me.SaveToSession("SupplierIDFilter_Ajax", Me.SupplierIDFilter.SelectedValue)
            HttpContext.Current.Session("AppRelatvieVirtualPath") = Me.Page.AppRelativeVirtualPath
         
        End Sub
        
        Protected Overrides Sub ClearControlsFromSession()
            MyBase.ClearControlsFromSession()

            ' Clear filter controls values from the session.
        
            Me.RemoveFromSession(Me.CategoryIDFilter)
            Me.RemoveFromSession(Me.ProductsSearchArea)
            Me.RemoveFromSession(Me.SupplierIDFilter)
            
            ' Clear table properties from the session.
            Me.RemoveFromSession(Me, "Order_By")
            Me.RemoveFromSession(Me, "Page_Index")
            Me.RemoveFromSession(Me, "Page_Size")
            
            Me.RemoveFromSession(Me, "DeletedRecordIds")  
            
        End Sub

        Protected Overrides Sub LoadViewState(ByVal savedState As Object)
            MyBase.LoadViewState(savedState)

            Dim orderByStr As String = CType(ViewState("ProductsTableControl_OrderBy"), String)
            If Not orderByStr Is Nothing AndAlso orderByStr.Trim <> "" Then
                Me.CurrentSortOrder = BaseClasses.Data.OrderBy.FromXmlString(orderByStr)
            Else
                Me.CurrentSortOrder = New OrderBy(True, True)
            End If

            Dim pageIndex As String = CType(ViewState("Page_Index"), String)
            If Not pageIndex Is Nothing Then
                Me.PageIndex = CInt(pageIndex)
            End If

            Dim pageSize As String = CType(ViewState("Page_Size"), String)
            If Not pageSize Is Nothing Then
                Me.PageSize = CInt(pageSize)
            End If
        
            Me.DeletedRecordIds = CType(Me.ViewState("DeletedRecordIds"), String)
        
        End Sub

        Protected Overrides Function SaveViewState() As Object
            
            If Not Me.CurrentSortOrder Is Nothing Then
                Me.ViewState("ProductsTableControl_OrderBy") = Me.CurrentSortOrder.ToXmlString()
            End If
            
            Me.ViewState("Page_Index") = Me.PageIndex
            Me.ViewState("Page_Size") = Me.PageSize
        
            Me.ViewState("DeletedRecordIds") = Me.DeletedRecordIds
        
            Return MyBase.SaveViewState()

        End Function

        ' Generate the event handling functions for pagination events.
        
        ' event handler for ImageButton
        Public Overridable Sub ProductsPagination_FirstPage_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                
            Me.PageIndex = 0
            Me.DataChanged = True
      
            Catch ex As Exception
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
    
            End Try
                  
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub ProductsPagination_LastPage_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                
            Me.DisplayLastPage = True
            Me.DataChanged = True
      
            Catch ex As Exception
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
    
            End Try
                  
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub ProductsPagination_NextPage_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                
            Me.PageIndex += 1
            Me.DataChanged = True
      
            Catch ex As Exception
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
    
            End Try
                  
        End Sub
            
        ' event handler for LinkButton
        Public Overridable Sub ProductsPagination_PageSizeButton_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Try
                
            Me.DataChanged = True
            Me.PageSize = Integer.Parse(Me.ProductsPagination.PageSize.Text)
            Me.PageIndex = Integer.Parse(Me.ProductsPagination.CurrentPage.Text) - 1
          
            Catch ex As Exception
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
    
            End Try
    
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub ProductsPagination_PreviousPage_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                
            If Me.PageIndex > 0 Then
                Me.PageIndex -= 1
                Me.DataChanged = True
            End If
      
            Catch ex As Exception
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
    
            End Try
                  
        End Sub
            

        ' Generate the event handling functions for sorting events.
        
        ' event handler for FieldSort
        Public Overridable Sub CategoryIDLabel1_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(ProductsTable.CategoryID)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(ProductsTable.CategoryID, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            
        ' event handler for FieldSort
        Public Overridable Sub DiscontinuedLabel_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(ProductsTable.Discontinued)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(ProductsTable.Discontinued, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            
        ' event handler for FieldSort
        Public Overridable Sub ProductNameLabel_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(ProductsTable.ProductName)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(ProductsTable.ProductName, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            
        ' event handler for FieldSort
        Public Overridable Sub QuantityPerUnitLabel_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(ProductsTable.QuantityPerUnit)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(ProductsTable.QuantityPerUnit, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            
        ' event handler for FieldSort
        Public Overridable Sub ReorderLevelLabel_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(ProductsTable.ReorderLevel)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(ProductsTable.ReorderLevel, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            
        ' event handler for FieldSort
        Public Overridable Sub SupplierIDLabel1_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(ProductsTable.SupplierID)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(ProductsTable.SupplierID, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            
        ' event handler for FieldSort
        Public Overridable Sub UnitPriceLabel_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(ProductsTable.UnitPrice)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(ProductsTable.UnitPrice, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            
        ' event handler for FieldSort
        Public Overridable Sub UnitsInStockLabel_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(ProductsTable.UnitsInStock)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(ProductsTable.UnitsInStock, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            
        ' event handler for FieldSort
        Public Overridable Sub UnitsOnOrderLabel_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(ProductsTable.UnitsOnOrder)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(ProductsTable.UnitsOnOrder, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            

        ' Generate the event handling functions for button events.
        
        ' event handler for ImageButton
        Public Overridable Sub ProductsCopyButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Dim url As String = "../Products/AddProductsPage.aspx?Products={PK}"
            Dim shouldRedirect As Boolean = True
            Dim TargetKey As String = Nothing
            Dim DFKA As String = Nothing
            Dim id As String = Nothing
            Dim value As String = Nothing
            Try
                DbUtils.StartTransaction
                
            url = Me.ModifyRedirectUrl(url, "",False)
            url = Me.Page.ModifyRedirectUrl(url, "",False)
                    Me.Page.CommitTransaction(sender)
          
            Catch ex As Exception
                Me.Page.RollBackTransaction(sender)
                shouldRedirect = False
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
          
            Finally
                DbUtils.EndTransaction
            End Try
            If shouldRedirect Then
                Me.Page.ShouldSaveControlsToSession = True
                Me.Page.Response.Redirect(url)
            ElseIf Not TargetKey Is Nothing AndAlso _
                        Not shouldRedirect Then
            Me.Page.ShouldSaveControlsToSession = True
            Me.Page.CloseWindow(True)
        
            End If              
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub ProductsDeleteButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                DbUtils.StartTransaction
                
            If(Not Me.Page.IsPageRefresh) Then
        
                Me.DeleteSelectedRecords(False)
          
            End If
                Me.Page.CommitTransaction(sender)
          
            Catch ex As Exception
                Me.Page.RollBackTransaction(sender)
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
          
            Finally
                DbUtils.EndTransaction
            End Try
                  
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub ProductsEditButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Dim url As String = "../Products/EditProductsPage.aspx?Products={PK}"
            Dim shouldRedirect As Boolean = True
            Dim TargetKey As String = Nothing
            Dim DFKA As String = Nothing
            Dim id As String = Nothing
            Dim value As String = Nothing
            Try
                DbUtils.StartTransaction
                
            url = Me.ModifyRedirectUrl(url, "",False)
            url = Me.Page.ModifyRedirectUrl(url, "",False)
                    Me.Page.CommitTransaction(sender)
          
            Catch ex As Exception
                Me.Page.RollBackTransaction(sender)
                shouldRedirect = False
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
          
            Finally
                DbUtils.EndTransaction
            End Try
            If shouldRedirect Then
                Me.Page.ShouldSaveControlsToSession = True
                Me.Page.Response.Redirect(url)
            ElseIf Not TargetKey Is Nothing AndAlso _
                        Not shouldRedirect Then
            Me.Page.ShouldSaveControlsToSession = True
            Me.Page.CloseWindow(True)
        
            End If              
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub ProductsExportButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                DbUtils.StartTransaction
                
          ' Build the where clause based on the current filter and search criteria
          ' Create the Order By clause based on the user's current sorting preference.
          
              Dim wc As WhereClause = CreateWhereClause
              Dim orderBy As OrderBy = Nothing
              
              orderBy = CreateOrderBy
              
          ' Add each of the columns in order of export.
          Dim columns() as BaseColumn = New BaseColumn() { _
                       ProductsTable.ProductName, _ 
             ProductsTable.SupplierID, _ 
             ProductsTable.CategoryID, _ 
             ProductsTable.QuantityPerUnit, _ 
             ProductsTable.UnitPrice, _ 
             ProductsTable.UnitsInStock, _ 
             ProductsTable.UnitsOnOrder, _ 
             ProductsTable.ReorderLevel, _ 
             ProductsTable.Discontinued, _ 
             Nothing}
            Dim rep as ExportData = New ExportData(ProductsTable.Instance, wc, orderBy, columns)
            rep.ExportToCSV(Me.Page.Response)
                  Me.Page.CommitTransaction(sender)
          
            Catch ex As Exception
                Me.Page.RollBackTransaction(sender)
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
          
            Finally
                DbUtils.EndTransaction
            End Try
                  
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub ProductsExportExcelButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                DbUtils.StartTransaction
                
            ' To customize the columns or the format, override this function in Section 1 of the page 
            ' and modify it to your liking.
            ' Build the where clause based on the current filter and search criteria
            ' Create the Order By clause based on the user's current sorting preference.
          
              Dim wc As WhereClause = CreateWhereClause
              Dim orderBy As OrderBy = Nothing
              
              orderBy = CreateOrderBy
              
            ' Create an instance of the Excel report class with the table class, where clause and order by.
            Dim excelReport as ExportData = New ExportData(ProductsTable.Instance, wc, orderBy)
            ' Add each of the columns in order of export.
            ' To customize the data type, change the second parameter of the new ExcelColumn to be
            ' a format string from Excel's Format Cell menu. For example "dddd, mmmm dd, yyyy h:mm AM/PM;@", "#,##0.00"
             excelReport.AddColumn(New ExcelColumn(ProductsTable.ProductName, "Default"))
             excelReport.AddColumn(New ExcelColumn(ProductsTable.SupplierID, "Default"))
             excelReport.AddColumn(New ExcelColumn(ProductsTable.CategoryID, "Default"))
             excelReport.AddColumn(New ExcelColumn(ProductsTable.QuantityPerUnit, "Default"))
             excelReport.AddColumn(New ExcelColumn(ProductsTable.UnitPrice, "$#,##0.00;($#,##0.00)"))
             excelReport.AddColumn(New ExcelColumn(ProductsTable.UnitsInStock, "0"))
             excelReport.AddColumn(New ExcelColumn(ProductsTable.UnitsOnOrder, "0"))
             excelReport.AddColumn(New ExcelColumn(ProductsTable.ReorderLevel, "0"))
             excelReport.AddColumn(New ExcelColumn(ProductsTable.Discontinued, "Default"))

            excelReport.ExportToExcel(Me.Page.Response)
                      Me.Page.CommitTransaction(sender)
          
            Catch ex As Exception
                Me.Page.RollBackTransaction(sender)
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
          
            Finally
                DbUtils.EndTransaction
            End Try
                  
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub ProductsImportButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Dim url As String = "../Shared/SelectFileToImport.aspx?TableName=Products"
            Try
                DbUtils.StartTransaction
                
            Dim script As String = "window.open('" &  Me.Page.EncryptUrlParameter(url) &  "','importWindow', 'width=700, height=500,top=' +(screen.availHeight-500)/2 + ',left=' + (screen.availWidth-700)/2+ ', resizable=yes, scrollbars=yes,modal=yes');"
            'If (Not Me.Page.ClientScript.IsStartupScriptRegistered("OpenPopup")) Then
            ScriptManager.RegisterStartupScript(Me.Page, Page.GetType(), "OpenPopup", script, true)
            'End If
                    Me.Page.CommitTransaction(sender)
          
            Catch ex As Exception
                Me.Page.RollBackTransaction(sender)
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
          
            Finally
                DbUtils.EndTransaction
            End Try
                  
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub ProductsNewButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Dim url As String = "../Products/AddProductsPage.aspx"
            Dim shouldRedirect As Boolean = True
            Dim TargetKey As String = Nothing
            Dim DFKA As String = Nothing
            Dim id As String = Nothing
            Dim value As String = Nothing
            Try
                DbUtils.StartTransaction
                
            url = Me.ModifyRedirectUrl(url, "",False)
            url = Me.Page.ModifyRedirectUrl(url, "",False)
                    Me.Page.CommitTransaction(sender)
          
            Catch ex As Exception
                Me.Page.RollBackTransaction(sender)
                shouldRedirect = False
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
          
            Finally
                DbUtils.EndTransaction
            End Try
            If shouldRedirect Then
                Me.Page.ShouldSaveControlsToSession = True
                Me.Page.Response.Redirect(url)
            ElseIf Not TargetKey Is Nothing AndAlso _
                        Not shouldRedirect Then
            Me.Page.ShouldSaveControlsToSession = True
            Me.Page.CloseWindow(True)
        
            End If              
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub ProductsPDFButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                DbUtils.StartTransaction
                
                Dim report As PDFReport = New PDFReport 
                report.SpecificReportFileName = Page.Server.MapPath("ShowProductsTablePage.ProductsPDFButton.report")
                ' report.Title replaces the value tag of page header and footer containing ${ReportTitle}
                report.Title = "Products"
                ' If ShowProductsTablePage.ProductsPDFButton.report specifies a valid report template,
                ' AddColumn method will generate a report template.   
                ' Each AddColumn method-call specifies a column
                ' The 1st parameter represents the text of the column header
                ' The 2nd parameter represents the horizontal alignment of the column header
                ' The 3rd parameter represents the text format of the column detail
                ' The 4th parameter represents the horizontal alignment of the column detail
                ' The 5th parameter represents the relative width of the column   			
                 report.AddColumn(ProductsTable.ProductName.Name, ReportEnum.Align.Left, "${ProductsTable.ProductName.Name}", ReportEnum.Align.Left, 28)
                 report.AddColumn(ProductsTable.SupplierID.Name, ReportEnum.Align.Left, "${ProductsTable.SupplierID.Name}", ReportEnum.Align.Left, 28)
                 report.AddColumn(ProductsTable.CategoryID.Name, ReportEnum.Align.Left, "${ProductsTable.CategoryID.Name}", ReportEnum.Align.Left, 15)
                 report.AddColumn(ProductsTable.QuantityPerUnit.Name, ReportEnum.Align.Left, "${ProductsTable.QuantityPerUnit.Name}", ReportEnum.Align.Left, 20)
                 report.AddColumn(ProductsTable.UnitPrice.Name, ReportEnum.Align.Right, "${ProductsTable.UnitPrice.Name}", ReportEnum.Align.Right, 20)
                 report.AddColumn(ProductsTable.UnitsInStock.Name, ReportEnum.Align.Right, "${ProductsTable.UnitsInStock.Name}", ReportEnum.Align.Right, 15)
                 report.AddColumn(ProductsTable.UnitsOnOrder.Name, ReportEnum.Align.Right, "${ProductsTable.UnitsOnOrder.Name}", ReportEnum.Align.Right, 15)
                 report.AddColumn(ProductsTable.ReorderLevel.Name, ReportEnum.Align.Right, "${ProductsTable.ReorderLevel.Name}", ReportEnum.Align.Right, 15)
                 report.AddColumn(ProductsTable.Discontinued.Name, ReportEnum.Align.Left, "${ProductsTable.Discontinued.Name}", ReportEnum.Align.Left, 15)

              Dim whereClause As WhereClause = CreateWhereClause
              
              Dim orderBy As OrderBy = CreateOrderBy
                
                Dim rowsPerQuery As Integer = 1000 
                Dim pageNum As Integer = 0 
                Dim recordCount As Integer = 0 
                Dim totalRecords As Integer = ProductsTable.GetRecordCount(whereClause)
                                
                report.Page = Page.GetResourceValue("Txt:Page", "Training1")
                report.ApplicationPath = Me.Page.MapPath(Page.Request.ApplicationPath)

                Dim columns As ColumnList = ProductsTable.GetColumnList()
                Dim records As ProductsRecord() = Nothing
                Do 
                    records = ProductsTable.GetRecords(whereClause, orderBy, pageNum, rowsPerQuery)
                    If Not (records Is Nothing) AndAlso records.Length > 0 AndAlso whereClause.RunQuery Then 
                        For Each record As ProductsRecord In records 
                            ' AddData method takes four parameters   
                            ' The 1st parameters represent the data format
                            ' The 2nd parameters represent the data value
                            ' The 3rd parameters represent the default alignment of column using the data
                            ' The 4th parameters represent the maximum length of the data value being shown
                             report.AddData("${ProductsTable.ProductName.Name}", record.Format(ProductsTable.ProductName), ReportEnum.Align.Left, 100)
                             report.AddData("${ProductsTable.SupplierID.Name}", record.Format(ProductsTable.SupplierID), ReportEnum.Align.Left, 100)
                             report.AddData("${ProductsTable.CategoryID.Name}", record.Format(ProductsTable.CategoryID), ReportEnum.Align.Left, 100)
                             report.AddData("${ProductsTable.QuantityPerUnit.Name}", record.Format(ProductsTable.QuantityPerUnit), ReportEnum.Align.Left, 100)
                             report.AddData("${ProductsTable.UnitPrice.Name}", record.Format(ProductsTable.UnitPrice), ReportEnum.Align.Right, 100)
                             report.AddData("${ProductsTable.UnitsInStock.Name}", record.Format(ProductsTable.UnitsInStock), ReportEnum.Align.Right, 100)
                             report.AddData("${ProductsTable.UnitsOnOrder.Name}", record.Format(ProductsTable.UnitsOnOrder), ReportEnum.Align.Right, 100)
                             report.AddData("${ProductsTable.ReorderLevel.Name}", record.Format(ProductsTable.ReorderLevel), ReportEnum.Align.Right, 100)
                             report.AddData("${ProductsTable.Discontinued.Name}", record.Format(ProductsTable.Discontinued), ReportEnum.Align.Left, 100)

                            report.WriteRow 
                        Next 
                        pageNum = pageNum + 1
                        recordCount += records.Length 
                    End If 
                Loop While Not (records Is Nothing) AndAlso recordCount < totalRecords  AndAlso whereClause.RunQuery 
                report.Close 
                BaseClasses.Utils.NetUtils.WriteResponseBinaryAttachment(Me.Page.Response, report.Title + ".pdf", report.ReportInByteArray, 0, true)
                    Me.Page.CommitTransaction(sender)
          
            Catch ex As Exception
                Me.Page.RollBackTransaction(sender)
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
          
            Finally
                DbUtils.EndTransaction
            End Try
                  
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub ProductsRefreshButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                
            DirectCast(Me.Page.FindControlRecursively("ProductsTableControl"), ProductsTableControl).ResetData = True
                
            Catch ex As Exception
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
          
            Finally
    
            End Try
                  
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub ProductsResetButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                
              Me.CategoryIDFilter.ClearSelection
              Me.SupplierIDFilter.ClearSelection
              Me.ProductsSearchArea.Text = ""
              Me.CurrentSortOrder.Reset()
              If Me.InSession(Me, "Order_By") Then
                  Me.CurrentSortOrder = OrderBy.FromXmlString(Me.GetFromSession(Me, "Order_By", Nothing))
              Else
                  Me.CurrentSortOrder = New OrderBy(True, True)
          
              End If
              

          Me.DataChanged = True
            
            Catch ex As Exception
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
          
            Finally
    
            End Try
                  
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub ProductsWordButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                DbUtils.StartTransaction
                
                Dim report As WordReport = New WordReport
                report.SpecificReportFileName = Page.Server.MapPath("ShowProductsTablePage.ProductsWordButton.report")
                ' report.Title replaces the value tag of page header and footer containing ${ReportTitle}
                report.Title = "Products"
                ' If ShowProductsTablePage.ProductsWordButton.report specifies a valid report template,
                ' AddColumn method will generate a report template.
                ' Each AddColumn method-call specifies a column
                ' The 1st parameter represents the text of the column header
                ' The 2nd parameter represents the horizontal alignment of the column header
                ' The 3rd parameter represents the text format of the column detail
                ' The 4th parameter represents the horizontal alignment of the column detail
                ' The 5th parameter represents the relative width of the column
                 report.AddColumn(ProductsTable.ProductName.Name, ReportEnum.Align.Left, "${ProductsTable.ProductName.Name}", ReportEnum.Align.Left, 28)
                 report.AddColumn(ProductsTable.SupplierID.Name, ReportEnum.Align.Left, "${ProductsTable.SupplierID.Name}", ReportEnum.Align.Left, 28)
                 report.AddColumn(ProductsTable.CategoryID.Name, ReportEnum.Align.Left, "${ProductsTable.CategoryID.Name}", ReportEnum.Align.Left, 15)
                 report.AddColumn(ProductsTable.QuantityPerUnit.Name, ReportEnum.Align.Left, "${ProductsTable.QuantityPerUnit.Name}", ReportEnum.Align.Left, 20)
                 report.AddColumn(ProductsTable.UnitPrice.Name, ReportEnum.Align.Right, "${ProductsTable.UnitPrice.Name}", ReportEnum.Align.Right, 20)
                 report.AddColumn(ProductsTable.UnitsInStock.Name, ReportEnum.Align.Right, "${ProductsTable.UnitsInStock.Name}", ReportEnum.Align.Right, 15)
                 report.AddColumn(ProductsTable.UnitsOnOrder.Name, ReportEnum.Align.Right, "${ProductsTable.UnitsOnOrder.Name}", ReportEnum.Align.Right, 15)
                 report.AddColumn(ProductsTable.ReorderLevel.Name, ReportEnum.Align.Right, "${ProductsTable.ReorderLevel.Name}", ReportEnum.Align.Right, 15)
                 report.AddColumn(ProductsTable.Discontinued.Name, ReportEnum.Align.Left, "${ProductsTable.Discontinued.Name}", ReportEnum.Align.Left, 15)

              Dim whereClause As WhereClause = CreateWhereClause
              
              Dim orderBy As OrderBy = CreateOrderBy
                
                Dim rowsPerQuery As Integer = 1000
                Dim pageNum As Integer = 0
                Dim recordCount As Integer = 0
                Dim totalRecords As Integer = ProductsTable.GetRecordCount(whereClause)

                report.Page = Page.GetResourceValue("Txt:Page", "Training1")
                report.ApplicationPath = Me.Page.MapPath(Page.Request.ApplicationPath)

                Dim columns As ColumnList = ProductsTable.GetColumnList()
                Dim records As ProductsRecord() = Nothing
                Do
                    records = ProductsTable.GetRecords(whereClause, orderBy, pageNum, rowsPerQuery)
                    If Not (records Is Nothing) AndAlso records.Length > 0 AndAlso whereClause.RunQuery Then
                        For Each record As ProductsRecord In records
                            ' AddData method takes four parameters
                            ' The 1st parameters represent the data format
                            ' The 2nd parameters represent the data value
                            ' The 3rd parameters represent the default alignment of column using the data
                            ' The 4th parameters represent the maximum length of the data value being shown
                             report.AddData("${ProductsTable.ProductName.Name}", record.Format(ProductsTable.ProductName), ReportEnum.Align.Left, 100)
                             report.AddData("${ProductsTable.SupplierID.Name}", record.Format(ProductsTable.SupplierID), ReportEnum.Align.Left, 100)
                             report.AddData("${ProductsTable.CategoryID.Name}", record.Format(ProductsTable.CategoryID), ReportEnum.Align.Left, 100)
                             report.AddData("${ProductsTable.QuantityPerUnit.Name}", record.Format(ProductsTable.QuantityPerUnit), ReportEnum.Align.Left, 100)
                             report.AddData("${ProductsTable.UnitPrice.Name}", record.Format(ProductsTable.UnitPrice), ReportEnum.Align.Right, 100)
                             report.AddData("${ProductsTable.UnitsInStock.Name}", record.Format(ProductsTable.UnitsInStock), ReportEnum.Align.Right, 100)
                             report.AddData("${ProductsTable.UnitsOnOrder.Name}", record.Format(ProductsTable.UnitsOnOrder), ReportEnum.Align.Right, 100)
                             report.AddData("${ProductsTable.ReorderLevel.Name}", record.Format(ProductsTable.ReorderLevel), ReportEnum.Align.Right, 100)
                             report.AddData("${ProductsTable.Discontinued.Name}", record.Format(ProductsTable.Discontinued), ReportEnum.Align.Left, 100)

                            report.WriteRow
                        Next
                        pageNum = pageNum + 1
                        recordCount += records.Length
                    End If
                Loop While Not (records Is Nothing) AndAlso recordCount < totalRecords AndAlso whereClause.RunQuery 
                report.save
                BaseClasses.Utils.NetUtils.WriteResponseBinaryAttachment(Me.Page.Response, report.Title + ".doc", report.ReportInByteArray, 0, true)
                    Me.Page.CommitTransaction(sender)
          
            Catch ex As Exception
                Me.Page.RollBackTransaction(sender)
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
          
            Finally
                DbUtils.EndTransaction
            End Try
                  
        End Sub
            
        ' event handler for Button with Layout
        Public Overridable Sub MarkDiscontinued_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Try
                
            Catch ex As Exception
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
          
            Finally
    
            End Try
    
        End Sub
            
        ' event handler for Button with Layout
        Public Overridable Sub ProductsSearchButton_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Try
                
          Me.DataChanged = True
      
            Catch ex As Exception
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
          
            Finally
    
            End Try
    
        End Sub
            
        ' event handler for Button with Layout
        Public Overridable Sub UnmarkDiscontinued_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Try
                
            Catch ex As Exception
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
          
            Finally
    
            End Try
    
        End Sub
            

        ' Generate the event handling functions for filter and search events.
        
        ' event handler for FieldFilter
        Protected Overridable Sub CategoryIDFilter_SelectedIndexChanged(ByVal sender As Object, ByVal args As EventArgs)
           Me.DataChanged = True
        End Sub
            
        ' event handler for FieldFilter
        Protected Overridable Sub SupplierIDFilter_SelectedIndexChanged(ByVal sender As Object, ByVal args As EventArgs)
           Me.DataChanged = True
        End Sub
            

        ' pagination properties
        Private _PageSize As Integer
        Public Property PageSize() As Integer
            Get
                Return Me._PageSize
            End Get
            Set(ByVal value As Integer)
                Me._PageSize = value
            End Set
        End Property

        Private _PageIndex As Integer
        Public Property PageIndex() As Integer
            Get
                ' Return the PageIndex
                Return Me._PageIndex
            End Get
            Set(ByVal value As Integer)
                Me._PageIndex = value
            End Set
        End Property

        Private _TotalRecords As Integer
        Public Property TotalRecords() As Integer
            Get
                Return Me._TotalRecords
            End Get
            Set(ByVal value As Integer)
                If Me.PageSize > 0 Then
                    Me.TotalPages = CInt(Math.Ceiling(value / Me.PageSize))
                End If

                Me._TotalRecords = value
            End Set
        End Property

        Private _TotalPages As Integer
        Public Property TotalPages() As Integer
            Get
                Return Me._TotalPages
            End Get
            Set(ByVal value As Integer)
                Me._TotalPages = value
            End Set
        End Property

        Private _DisplayLastPage As Boolean
        Public Property DisplayLastPage() As Boolean
            Get
                Return Me._DisplayLastPage
            End Get
            Set(ByVal value As Boolean)
                Me._DisplayLastPage = value
            End Set
        End Property

        Private _DataChanged As Boolean = False
        Public Property DataChanged() As Boolean
            Get
                Return Me._DataChanged
            End Get
            Set(ByVal value As Boolean)
                Me._DataChanged = value
            End Set
        End Property
        
        Private _ResetData As Boolean = False
        Public Property ResetData() As Boolean
            Get
                Return Me._ResetData
            End Get
            Set(ByVal value As Boolean)
                Me._ResetData = value
            End Set
        End Property

        Private _AddNewRecord As Integer = 0
        Public Property AddNewRecord() As Integer
            Get
                Return Me._AddNewRecord
            End Get
            Set(ByVal value As Integer)
                Me._AddNewRecord = value
            End Set
        End Property

        Private _CurrentSortOrder As OrderBy = Nothing
        Public Property CurrentSortOrder() As OrderBy
            Get
                Return Me._CurrentSortOrder
            End Get
            Set(ByVal value As BaseClasses.Data.OrderBy)
                Me._CurrentSortOrder = value
            End Set
        End Property

        Private _DataSource() As ProductsRecord = Nothing
        Public Property DataSource() As ProductsRecord ()
            Get
                Return Me._DataSource
            End Get
            Set(ByVal value() As ProductsRecord)
                Me._DataSource = value
            End Set
        End Property

#Region "Helper Properties"
        
        Public ReadOnly Property CategoryIDFilter() As System.Web.UI.WebControls.DropDownList
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CategoryIDFilter"), System.Web.UI.WebControls.DropDownList)
            End Get
        End Property
        
        Public ReadOnly Property CategoryIDLabel() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CategoryIDLabel"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
        
        Public ReadOnly Property CategoryIDLabel1() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CategoryIDLabel1"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
        Public ReadOnly Property DiscontinuedLabel() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "DiscontinuedLabel"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
        Public ReadOnly Property MarkDiscontinued() As Training1.UI.IThemeButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "MarkDiscontinued"), Training1.UI.IThemeButton)
          End Get
          End Property
        
        Public ReadOnly Property ProductNameLabel() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductNameLabel"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
        Public ReadOnly Property ProductsCopyButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsCopyButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property ProductsDeleteButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsDeleteButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property ProductsEditButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsEditButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property ProductsExportButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsExportButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property ProductsExportExcelButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsExportExcelButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property ProductsImportButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsImportButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property ProductsNewButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsNewButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property ProductsPagination() As Training1.UI.IPagination
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsPagination"), Training1.UI.IPagination)
          End Get
          End Property
        
        Public ReadOnly Property ProductsPDFButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsPDFButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property ProductsRefreshButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsRefreshButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property ProductsResetButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsResetButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property ProductsSearchArea() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsSearchArea"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
        
        Public ReadOnly Property ProductsSearchButton() As Training1.UI.IThemeButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsSearchButton"), Training1.UI.IThemeButton)
          End Get
          End Property
        
        Public ReadOnly Property ProductsTitle() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsTitle"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
        
        Public ReadOnly Property ProductsToggleAll() As System.Web.UI.WebControls.CheckBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsToggleAll"), System.Web.UI.WebControls.CheckBox)
            End Get
        End Property
        
        Public ReadOnly Property ProductsTotalItems() As System.Web.UI.WebControls.Label
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsTotalItems"), System.Web.UI.WebControls.Label)
            End Get
        End Property
        
        Public ReadOnly Property ProductsWordButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ProductsWordButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property QuantityPerUnitLabel() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "QuantityPerUnitLabel"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
        Public ReadOnly Property ReorderLevelLabel() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ReorderLevelLabel"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
        Public ReadOnly Property SupplierIDFilter() As System.Web.UI.WebControls.DropDownList
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "SupplierIDFilter"), System.Web.UI.WebControls.DropDownList)
            End Get
        End Property
        
        Public ReadOnly Property SupplierIDLabel() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "SupplierIDLabel"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
        
        Public ReadOnly Property SupplierIDLabel1() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "SupplierIDLabel1"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
        Public ReadOnly Property UnitPriceLabel() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "UnitPriceLabel"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
        Public ReadOnly Property UnitsInStockLabel() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "UnitsInStockLabel"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
        Public ReadOnly Property UnitsOnOrderLabel() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "UnitsOnOrderLabel"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
        Public ReadOnly Property UnmarkDiscontinued() As Training1.UI.IThemeButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "UnmarkDiscontinued"), Training1.UI.IThemeButton)
          End Get
          End Property
        
#End Region

#Region "Helper Functions"
        
           Public Overrides Overloads Function ModifyRedirectUrl(url As String, arg As String, ByVal bEncrypt As Boolean) As String
            Dim needToProcess As Boolean = AreAnyUrlParametersForMe(url, arg)
            If (needToProcess) Then
                Dim recCtl As ProductsTableControlRow = Me.GetSelectedRecordControl()
                If recCtl Is Nothing AndAlso url.IndexOf("{") >= 0 Then
                    ' Localization.
                    Throw New Exception(Page.GetResourceValue("Err:NoRecSelected", "Training1"))
                End If

                Dim rec As ProductsRecord = Nothing
                If Not recCtl Is Nothing Then
                    rec = recCtl.GetRecord()
                End If
                Return ModifyRedirectUrl(url, arg, rec, bEncrypt)
            End If
            Return url
        End Function
          
        Public Function GetSelectedRecordIndex() As Integer
            Dim counter As Integer = 0
            Dim recControl As ProductsTableControlRow
            For Each recControl In Me.GetRecordControls()
                If recControl.ProductsRecordRowSelection.Checked Then
                    Return counter
                End If
                counter += 1
            Next
            Return -1
        End Function
        
        Public Function GetSelectedRecordControl As ProductsTableControlRow
            Dim selectedList() As ProductsTableControlRow = Me.GetSelectedRecordControls()
            If selectedList.Length = 0 Then
                Return Nothing
            End If
            Return selectedList(0)
          
        End Function

        Public Function GetSelectedRecordControls() As ProductsTableControlRow()
        
            Dim selectedList As ArrayList = New ArrayList(25)
            Dim recControl As ProductsTableControlRow
            For Each recControl In Me.GetRecordControls()
                If recControl.ProductsRecordRowSelection.Checked Then
                    selectedList.Add(recControl)
                End If
            Next
            Return DirectCast(selectedList.ToArray(GetType(ProductsTableControlRow)), ProductsTableControlRow())
          
        End Function

        Public Overridable Sub DeleteSelectedRecords(ByVal deferDeletion As Boolean)
            Dim recList() As ProductsTableControlRow = Me.GetSelectedRecordControls()
            If recList.Length = 0 Then
                ' Localization.
                Throw New Exception(Page.GetResourceValue("Err:NoRecSelected", "Training1"))
            End If
            
            Dim recCtl As ProductsTableControlRow
            For Each recCtl In recList
                If deferDeletion Then
                    If Not recCtl.IsNewRecord Then
                
                        Me.AddToDeletedRecordIds(recCtl)
                  
                    End If
                    recCtl.Visible = False
                
                    recCtl.ProductsRecordRowSelection.Checked = False
                
                Else
                
                    recCtl.Delete()
                    Me.DataChanged = True
                    Me.ResetData = True
                  
                End If
            Next
        End Sub

        Public Function GetRecordControls() As ProductsTableControlRow()
            Dim recList As ArrayList = New ArrayList()
            Dim rep As System.Web.UI.WebControls.Repeater = CType(Me.FindControl("ProductsTableControlRepeater"), System.Web.UI.WebControls.Repeater)
            Dim repItem As System.Web.UI.WebControls.RepeaterItem

            For Each repItem In rep.Items
                Dim recControl As ProductsTableControlRow = DirectCast(repItem.FindControl("ProductsTableControlRow"), ProductsTableControlRow)
                recList.Add(recControl)
            Next

            Return DirectCast(recList.ToArray(GetType(ProductsTableControlRow)), ProductsTableControlRow())
        End Function

        Public Shadows ReadOnly Property Page() As BaseApplicationPage
            Get
                Return DirectCast(MyBase.Page, BaseApplicationPage)
            End Get
        End Property

#End Region

    

End Class

  

#End Region
    
  
End Namespace

  